一、字符串基础特性

  • 字符串是 不可变对象(immutable)
  • 支持索引 s[0]、切片 s[1:4]、遍历 for c in s
  • 支持 + 拼接、* 重复:"ab" * 3 → "ababab"
1
2
3
s = "Hello"
print(s[0]) # 'H'
print(s[::-1]) # 'olleH'(反转)

二、常用字符串方法(按功能分类)

字符判断类(返回 True/False

方法 功能 示例
.isalpha() 是否全是字母 "abc".isalpha()True
.isdigit() 是否全是数字(0-9) "123".isdigit()True
.isalnum() 是否是字母或数字 "a1".isalnum()True
.isspace() 是否全是空白字符 " \t\n".isspace()True
.islower() 是否全是小写 "hello".islower()True
.isupper() 是否全是大写 "HELLO".isupper()True
.istitle() 是否是标题格式(首字母大写) "Hello".istitle()True
.startswith(prefix) 是否以某字符串开头 "abc".startswith("a")True
.endswith(suffix) 是否以某字符串结尾 "file.txt".endswith(".txt")True

⚠️ 注意:isdigit() 不识别负数、小数;-123str"-123".isdigit()False


Read more »

python中的对象

1
2
3
4
5
6
7
8
9
10
11
12
def apple():
print("there is an apple")

# 1. 函数对象
apple

# 2.执行apple函数
apple()

# 3.将变量obj指向apple对象,执行apple函数
obj = apple
obj()

注意这里apple 和 apple() 的区别

Read more »