目录
3.1字符串基本操作
包括序列的一些基本操作,如索引,切片,乘法,成员资格检查,长度,最小/大值等。当然,字符串不可变。
3.2设置字符串格式:精简版
暂时只写精简版,完整版以后再看。
1.使用字符串格式设置符%
这是比较老的一种方法(莫名想到c),在%左边设定一个字符串(格式字符串),并在右边指定要设置其格式的值。右边可以是元组/字符串/字典等。
>>> format = 'hello,%s. how are %s ?'
>>> values = ('Tom','you')
>>> format % values
'hello,Tom. how are you ?'
2.使用模板字符串
>>> from string import Template
>>> tmpl = Template('Hello,$who!$what enough for ya?')
>>> tmpl.substitute(who='Mars',what='Dusty')
'Hello,Mars!Dusty enough for ya?'
3.使用字符串方法format
现在比较推荐的一种方法。每个替换字段都用花括号括起,其中可能包含名称,还可能包含有关如何应对相应的值进行转换和格式设置的信息。
#最简单的情况下,替换字段没有名称和索引
>>> '{},{} and {}'.format('first','second','third')
'first,second and third'
#索引
>>> '{0},{1} and {2}'.format('first','second','third')
'first,second and third'
>>> "{3} {0} {2} {1} {3} {0}".format("be","not","or","to")
'to be or not to be'
#也可以用命名字段的方式
>>> "{name}的值为:{value:.2f}".format(name="pi",value=3.1415926)
'pi的值为:3.14'
#变量与替换字段相同,可以直接使用,只要在前面加前缀f
>>> name = 'wxc'
>>> f'my name is {name}'
'my name is wxc'
3.4字符串方法
3.4.1 center
通过在两边添加填充字符(默认为空格)让字符串居中。
>>> "center".center(10,"*")
'**center**'
#第一个值为填充后的长度,后一个为填充字符(省略则默认为空格)
3.4.2 find
在字符串中查找子串,如果找到,就返回字串的第一个字符的索引,否则返回-1。你还可以指定搜索的起点和终点。注意与in的不同。
>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('Get',0,5)
-1
3.4.3 join
str.join(sequence)用于合并序列的元素(好像元素只能是字符串),返回的一定是字符串,所以常用来将其他数据结构转换为字符串。与split相反。
>>> a = ['1','2','3']
>>> b = '+'
>>> b.join(a)#而a.join(b)是不对的
'1+2+3'
>>> dirs = '','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'
3.4.4 lower
返回字符串的小写版本。
>>> name = 'Tom'
>>> names =['tom','amy','tony']
>>> name.lower() in names
True
词首大写:title和string中的sapwords
>>> 'hello ,world'.title()
'Hello ,World'
>>> "that's all folks".title()#然而有时候会这样
"That'S All Folks"
>>> import string
>>> string.capwords("that's all folks")
"That's All Folks"
3.4.5 replace
将指定字串都替换为另一个字符串,并返回替换后的结果。
>>> 'This is a test'.replace('is','emmmmm')
'Themmmmm emmmmm a test'
3.4.6 split
将字符串拆分为序列。如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格,制表符,换行符等)处进行拆分
>>> '1+2+3'.split('+')
['1', '2', '3']
>>> 'Using the default'.split()
['Using', 'the', 'default']
3.4.7 strip
将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果。当然,也可以传入想要删除的字符。
>>> '!!! emmmmm ***!'.strip('! ')
'emmmmm ***'
3.4.8 translate
与replace类似,但是只能进行但字符的替换。它的优势在于能够同时替换多个字符,但是需要先创建一个转换表,str.maketrans()。
>>> table = str.maketrans('cs', 'kz')
>>> table
{99: 107, 115: 122}
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
3.4.9 判断字符串是否满足特定的条件
以is开头的多是判断特定的性质。如isspace(判断是否为空白),isdigit(是否全为数字)等。。。。