1.首字母大写
s = 'xia'
s1 = s.capitalize()
print (s1)
Xia
2.全大写,全小写
s2 = s.upper()
s21 = s.lower()
print ("s2:",s2)
print ('s21:',s21)
s2: XIA
s21: xia
3.大小写反转
s3 = s.swapcase()
print (s3)
XIA
4.首字母大写(每个隔开的,或者是特殊字符(包括数字)隔开)
s = 'alex egon2wu*xia'
s4 = s.title()
print (s4)
Alex Egon2Wu*Xia
5.居中填充
s = 'alexwusir'
s5 = s.center(20,'*')#20:字符串长度,#:用'#'填充,默认使用空格填充
print (len(s5))
print (s5)
20
00000alexwusir000000
6.判断字符串以什么开始(startswith),或者是以什么结尾(endswith)
s = 'alex wu sir'
s6 = s.startswith('alex',)
s61 = s.startswith('wu',5,7)#判断'wu'是不是在索引[5,7)中
s62 = s.endswith('11')
print (s6,s61,s62)
True True False
7.按索引查找字符
s = 'alexwusir'
s7 = s.find('e')
s71 = s.find('x',2,6)#索引从[2,6)中找
s72 = s.index('e')
print (s7,s71,s72)
2 3 2
8.删除特定字符
s = ' ###alex***'
s8 = s.strip()#从头开始,默认删除空格
s81 = s.rstrip('*')#从右开始
s82 = s9.lstrip('#')#从左开始
print ('s8:',s8)
print ('s81:',s81)
print ('s82:',s82)
s8: ###alex***
s81: ###alex
s82: alex***
9.计算某个字符出现的次数
s = 'aoligeigan'
print (s.count('g'))
2
10.一些判断
s1 = '2222'
s2 = 'A2222'
print (s1.isdigit())
print (s2.istitle())#判断字符串首字母是否是大写
True
True
11.分割
s = 'alex wu sir'
l = s.split()#默认按空格分割,并以列表形式返回
print (l)
[‘alex’, ‘wu’, ‘sir’]
12.替换
s = 'aabbcc'
s12 = s.replace('b','0')#用0替换b
print (s12)
aa00cc
13.格式化输出
第一种形式:“字符串”%(…)
name='巨魔'
age = 38
slogan = '奥利给'
msg = '我叫%s,今年%s,%s'%(name,age,slogan)
print (msg)
我叫巨魔,今年38,奥利给
第二种形式:“字符串”.format(…)
name='巨魔'
age = 38
slogan = '奥利给'
msg = '我叫{0},今年{1},{2},{2}'.format(name,age,slogan)
print (msg)
我叫巨魔,今年38,奥利给,奥利给
来源:CSDN
作者:骚火棍
链接:https://blog.csdn.net/Galen_xia/article/details/103744971