栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python学习笔记——字符串方法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python学习笔记——字符串方法

center:用来在两边填充字符,让字符串居中
'the middle is sssssss'.center(20)
'            The middle is lx           '

strip:删除开头结尾空白字符
'            The middle is lx           '.strip()
'The middle is lx'
names=['lx','dt','xx']

>> name='lx '
>> if name in names: print('this is true')
...
>> if name.strip() in names: print('this is true')
...
this is true

find:在字符串中查找子串,返回第一次出现子串的索引
'The middle is lx'.find('lx')
14

join:合并字符串序列元素
seq=['1','2','3','4','5']

>> sep.join(seq)
'1+2+3+4+5‘

split:拆分字符串序列
seq='1+2+3+4+5+6'

>> seq().split('+')
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object is not callable
>> seq.split('+')
['1', '2', '3', '4', '5', '6']
>> sep=seq.split('+')
>> sep
['1', '2', '3', '4', '5', '6']

lower:返回字符串小写版本

'TTT111'.lower()
'ttt111'

replace:将指定字符串替换为另一个字符串。并返回替换后结果
this is a test'.replace('is','are')
'thare are a test'

>> 'this is a test'.replace('is','ere')
'there ere a test'

translate:替换字符串特定部分,只能单字符替换
要预先设定好转换表,可采用str.maketrans('cs','kz')这种,maketrans接受两个参数,两个长度相同的字符串,指定前一个字符串被后一个字符串替换,可以设定第三个参数为要删除的指定字符,如空格
table=str.maketrans('cs','kz','')

>> 'ffccctttsss  sssssss'.translate(table)
'ffkkktttzzz  zzzzzzz'
>> 'ffccctttsss sssssss'.translate(table)
'ffkkktttzzz zzzzzzz'
>> table=str.maketrans('cs','kz',' ')
>> 'ffccctttsss sssssss'.translate(table)
'ffkkktttzzzzzzzzzz'

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/225121.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号