python 字符串的常用操作
stri = 'name is knochkapoor'
capltalize #首字母大写
print(stri.capitalize()) 输出结果:Name is knochkapoor
casefold #大写转小写
print(stri.casefold()) 输入结果:name is knochkapoor
count #统计字符出现的次数
print(stri.count('o'))
centor #字符两边用指定字符补全
print(stri.center(50,'-')) 输出结果:---------------name is knochkapoor----------------
ljust #字符串不够的在右边用指定字符补全,与rjust相反
print(stri.ljust(50,'_')) 输出结果:name is knochkapoor_______________________________
encode #二进制转换
print(stri.encode()) 输出结果:b'name is knochkapoor' print('吴京'.encode()) 输出结果:b'\xe5\x90\xb4\xe4\xba\xac'
startswith & endswith #以什么字符开始&结束
print(str.startswith('ka') #字符以什么开始 print(stri.endswith('r')) #字符以什么结尾
find #查找字符,字符串可以通过find进行切片
print(stri.find('knoch')) #查找字符位置 print(stri[stri.find('knoch'):13]) #通过字符串的切片,把knoch取出来
rfind #查找最右边的指定字符
print('knochnapoor'.rfind('o')) 输出结果:9
format #格式化输出
name = 'my nema is {name} and i an {year} old' print(name.format(name = 'knoch',year = 22)) #指定字符格式化输出 print(name.format_map({'name':'knoch','year':22})) #常用于字典 #输出结果是一样的 my nema is knoch and i an 22 old my nema is knoch and i an 22 old
isalnum #判断是不是阿拉伯字符
'a12'.isalnum() #True
isalpha #判断是不是纯英文字符
print('a12'.isalpha()) #False
isdecimal #判断是不是十进制数字
print('11'.isdecimal()) #True
isdigit #判断是不是整 数
print('11'.isdigit()) #True
isidentifier #判断是不是合法的标识符
print('abc'.isidentifier()) #True
islower & isupper #判断大小写
'abc'.islower() 'ABC'.inupper()
isspace #判断是不是空格
print('33a'.isspace()) 输出结果:False
istitle #每个首字母大写
print('My Name Is Knoch'.istitle()) #True
join #将一个列表的元素或一个字符串用指定的字符隔开
1,列表 lst = ['ales','knoch'] print(' '.join(lst)) #将一个列表和字符串用指字的字符分隔开 输出结果:ales knoch 2,字符串 ddd = 'knochkapoor' print('_'.join(ddd)) 输入结果:k_n_o_c_h_k_a_p_o_o_r:
lower & upper
'ABC'.lower 'abc'.upper 输出结果:‘abc','ABC'
strip #去掉字符两个的空格和回车,lstrip去左边的,rstrip去右边的
print(' knoch '.strip()) #输出结果:knoch
split #将字符串按照指定的字符分开并转换成列表
print('1+2+3+4'.split('+')) 输入结果:['1','2','3','4']
maketrans #转换并匹配
p = str.maketrans('abcdef','123456') print('alex li'.translate(p)) #输出结果: 1l5x li
swapcase #将一串字符串里的大写转小写,小写转大写
print('KNochkaPooR'.swapcase()) 输出结果:knOCHKApOOr
zfill #将指定长度不足的字符用0补位
print('knochkapoor'.zfill(20)) 输出结果:000000000knochkapoor

浙公网安备 33010602011771号