所有标准序列操作(索引、切片、乘法、成员资格检查、长度、最小值和最大值)都适用于字符串,但别忘了字符串是不可变的,因此所有的元素赋值和切片赋值都是非法的。
格式化
转换说明符
在Python中,采用的格式化方式和C语言是一致的,用%实现,举例如下:
>>> 'Hello, %s' % 'world''Hello, world'>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)'Hi, Michael, you have $1000000.'
%运算符就是用来格式化字符串的。
在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。
其中,格式化整数和浮点数还可以指定是否补0和整数与小数的位数:
print('%2d-%02d' % (3, 1)) # 3-01 (%2d 两位整数,不足的默认用空格补充)# (%02d 两位整数,不足的用0补充)print('%.2f' % 3.1415926) #3.14 (%.2f保留两位小数)
%2d是将数字按宽度为2,采用右对齐方式输出,若数据位数不到2位,则左边补空格%02d,和%2d差不多,只不过左边补0%.2d和%02d一样
字符串里面的%是一个普通字符怎么办?这个时候就需要转义,用%%来表示一个%:
>>> 'growth rate: %d %%' % 7'growth rate: 7 %'
format()
另一种格式化字符串的方法是使用字符串的format()方法,它会用传入的参数依次替换字符串内的占位符{0}、{1}……,不过这种方式写起来比%要麻烦得多:
# 最简单的情况下,替换字段没有名称或将索引用做名称。>>> '{}, {} and {}'.format('first', 'second', 'thrid')'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'# 命名字段>>> from math import pi>>> '{name} is approximately {value:.2f}'.format(value=pi, name='π')'π is approximately 3.14.'# 混合使用未命名参数或索引指定,和命名字段>>> '{foo} {} {bar} {}'.format(1,2,bar=4,foo=3)'3 1 4 2'>>> '{foo} {1} {bar} {0}'.format(1,2,bar=4,foo=3)'3 2 4 1'# 不能同时使用手工编号和自动编号,因为这样很快会变得混乱不堪。>>> fullname = ["Alfred", "Smoketoomuch"]>>> "Mr {name[1]}".format(name=fullname)
宽度、精度和千位分隔符
# 宽度是使用整数指定的,如下所示:>>> "{num:10}".format(num=3)' 3'>>> "{name:10}".format(name="Bob")'Bob '# 数和字符串的对齐方式不同
f-string
在Python 3.6中,如果变量与替换字段同名,可使用f字符串——在字符串前面加上f。以f开头的字符串,字符串如果包含{xxx},就会以对应的变量替换:
>>> r = 2.5>>> s = 3.14 * r **2>> print(f'The area of a circle with radius {r} is {s:.2f}')The area of a circle with radius 2.5 is 19.62
字符串方法
center
通过在两边添加填充字符(默认为空格)让字符串居中。
>>> "The Middle by Jimmy Eat World".center(39)' The Middle by Jimmy Eat World '>>> "The Middle by Jimmy Eat World".center(39, '*')'*****The Middle by Jimmy Eat World*****'
相关方法: ljust、rjust和zfill
find
在字符串中查找子串。如果找到就返回子串的第一个字符的索引,否则返回-1。
>>> 'With a moo-moo here, and a moo-moo there'.find('moo')7>>> title = "Monty Python's Flying Circus">>> title.find('Monty')0>>> title.find('Zirquss')-1
还可指定搜索的起点和终点。
>>> subject = '$$$ Get rich now!!! $$$'>>> subject.find('$$$')0>>> subject.find('$$$', 1) # 只指定了起点20>>> subject.find('!!!', 0, 16) # 同时指定了起点和终点-1
注意: 起点和终点指定的搜索范围包含起点,但不包含终点。这是Python惯常的做法。
相关方法: rfind、index、rindex、count、startswith、endswith。
join
合并序列的元素。
>>> seq = ['1','2','3','4','5']>>> sep = '+'>>> sep.join(seq) # 尝试合并一个字符串列表'1+2+3+4+5'>>> dirs = '', 'usr', 'bin', 'env'>>> '/'.join(dirs)'/usr/bin/env'
相关方法: split
lower
返回字符串的小写版本。
>>> 'Trondheim Hammer Dance'.lower()'trondheim hammer dance'
相关方法: islower、istitle、isupper、translatecapitalize、casefold、seapcase、title、upper。
replace
将指定子串都替换为另一个字符串,并返回替换后的结果
>>> 'This is test'.replace('is', 'eez')'Theez eez a test'
相关方法:translate、expandtabs。
split
作用与join相反,用于将字符串拆分为序列。
'1+2+3+4+5'.split('+')['1','2','3','4','5']>>> 'Using the default'.split()['Using', 'the', 'default']
如果没有指定分隔符,将默认在单个或多个连续的空白字符处进行拆分。
相关方法:join、partition、rpartition、rsplit、splitlines。
strip
将字符串开头和末尾的空白删除,并返回删除后的结果。
>>> ' internal whitespace is kept '.strip()'internal whitespace is kept'
还可以在一个字符串参数中指定要删除哪些字符。
'*** SPAM * for * everyone!!! ***'.strip(' *!')'SPAM * for *evenyone'
相关方法: lstrip、rstrip。
translate
与replace一样替换字符串的特定部分,但不同的是它只能进行单字符替换。
优势在于能够同时替换多个字符,因此效率比replace高。
使用translate前必须创建一个转换表。这个转换表指出了不同Unicode码点之间的转
换关系。要创建转换表,可对字符串类型str调用方法maketrans,这个方法接受两个参数:两个长度相同的字符串,它们指定要将第一个字符串中的每个字符都替换为第二个字符串中的相应字符。
>>> table = str.maketrans('cs', 'kz')>>> table{115: 122, 99: 107}
创建转换表后,就可将其用作方法translate的参数。
>>> 'this is an incredible test'.translate(table)'thiz iz an inkredible tezt'# 第三个参数(可选),指定要将哪些字母删除。>>> table = str.maketrans('cs', 'kz', ' ')>>> 'this is an incredible test'.translate(table)'thizizaninkredibletezt'
相关方法: replace、lower。
判断字符串是否满足特定的条件
很多字符串方法都以is打头,如isspace、isdigit和isupper,它们判断字符串是否具特定的性质(如包含的字符全为空白、数字或大写)。如果字符串具备特定的性质,这些方法就返回True,否则返回False。
附录B:isalnum、isalpha、isdecimal、isdigit、isidentifier、islower、isnumeric、isprintable、isspace、istitle、isupper。
