字符串
序列操作(列表、元组亦可用)
len函数返回长度
a = 'hello,world!'
print(len(a))
12
索引操作得到各元素
a = 'hello,world!'
print(a[0]) # 正向索引
print(a[1])
print(a[-1]) # 反向索引
h
e
!
切片
一般形式:X[I:J],意思是从 偏移量 I 一直取到 偏移量 J 但不包括 偏移量 J
或者说:从 开始索引 I 一直取到 结束索引 J 但不包括 结束索引 J
a = '0123456'
print(f"字符串 '0123456' 切片: \n\t"
f"a[1:3]: {a[1:3]}\n\t"
f"a[:]: {a[:]}\n\t"
f"a[1:]: {a[1:]}\n\t"
f"a[:3]: {a[:3]}\n\t"
f"a[0:3]: {a[0:3]}\n\t"
f"a[1:-1]: {a[1:-1]}")
字符串 '0123456' 切片:
a[1:3]: 12
a[:]: 0123456
a[1:]: 123456
a[:3]: 012
a[0:3]: 012
a[1:-1]: 12345
字符串[开始索引:结束索引:步长]
print(a[::2])
print(a[::-1]) # 逆序
0246
6543210
拼接
x = 'oh'
y = 'god'
print(x+y)
print(x*3)
print(x*3+y)
ohgod
ohohoh
ohohohgod
不可变性
字符串生成后,就不会改变,我们的切片和拼接都是新建了一个新的字符串
a = '11111'
a[0] = '2' # 把第一个1换成2
TypeError: 'str' object does not support item assignment
类型错误:‘str'对象不支持项赋值
我们可以新建一个字符串,并用旧名字命名,python运行中会清理掉旧对象
a = '11111'
a = '2'+a[1:]
print(a)
21111
字符串特定方法
- find(子字符串):返回子字符串在父字符串中的开始索引,若没找到,就会返回**-1**。
a = 'how old are you?'
print(a.find('old'))
4
- replace():搜索并替换。(注意,这是新建了一个字符串)
a = 'how old are you?'
print(a.replace('are you','is he'))
how old is he?
- .split(分隔符,拆分次数):以括号内的东西作为分隔符,分隔字符串为列表。(不填分隔符,即默认以空格和换行符为分隔符)(拆分次数默认-1,即全拆,若指定次数,则不会超过能拆分的最多次数)
a = 'how old are you?'
print(a.split(' ')) # 填了字符串空格,即’ ‘
print(a.split()) # 啥都没填
['how', 'old', 'are', 'you?']
['how', 'old', 'are', 'you?']
注意:连续的分隔符不会被组合,只会单算,从而分隔出空字符串
b = '1,,2'
print(b.split(','))
['1', '', '2']
拆分次数演示,显然超过
a = '111 222 333 444'
print(a.split(' ')) # 默认能拆的全拆了
print(a.split(' ',1))
print(a.split(' ',2))
print(a.split(' ',3))
print(a.split(' ',4))
['111', '222', '333', '444']
['111', '222 333 444']
['111', '222', '333 444']
['111', '222', '333', '444']
['111', '222', '333', '444']
大小写
- .title():首字母大写
- .upper():全部大写
- .lower():全部小写
a = 'oh oh oh'
a = a.title()
print(a)
print(a.upper())
print(a.lower())
Oh Oh Oh
OH OH OH
oh oh oh
判断
- .isdigit():判断字符串是否由数字构成
- .isalpha():判断字符串是否由字母构成
- .isalnum():判断字符串是否由数字和字母构成
a = 'abc'
print(a.isdigit())
print(a.isalpha())
print(a.isalnum())
False
True
True
空白
添加空白
换行符:\n
制表符:\t
print('123\n321')
print('abc\tcbd')
print('家:\n\t爸爸\n\t妈妈\n\t我')
123
321
abc cbd
家:
爸爸
妈妈
我
删除空白
- .rstrip():删除右侧空白
- .lstrip():删除左侧空白
- .strip():删除两侧空白
x = ' hi world '
print(f"《{x}》")
print(f"《{x.rstrip()}》")
print(f"《{x.lstrip()}》")
print(f"《{x.strip()}》")
《 hi world 》
《 hi world》
《hi world 》
《hi world》