所有标准序列操作(索引、切片、乘法、成员资格检查、长度、最小值和最大值)都适用于字符串,但别忘了字符串是不可变的,因此所有的元素赋值和切片赋值都是非法的。

格式化

转换说明符

在Python中,采用的格式化方式和C语言是一致的,用%实现,举例如下:

  1. >>> 'Hello, %s' % 'world'
  2. 'Hello, world'
  3. >>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
  4. 'Hi, Michael, you have $1000000.'

%运算符就是用来格式化字符串的。

在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。

其中,格式化整数和浮点数还可以指定是否补0和整数与小数的位数:

  1. print('%2d-%02d' % (3, 1)) # 3-01 (%2d 两位整数,不足的默认用空格补充)
  2. # (%02d 两位整数,不足的用0补充)
  3. print('%.2f' % 3.1415926) #3.14 (%.2f保留两位小数)

%2d是将数字按宽度为2,采用右对齐方式输出,若数据位数不到2位,则左边补空格
%02d,和%2d差不多,只不过左边补0
%.2d%02d一样

字符串里面的%是一个普通字符怎么办?这个时候就需要转义,用%%来表示一个%:

  1. >>> 'growth rate: %d %%' % 7
  2. 'growth rate: 7 %'

format()

另一种格式化字符串的方法是使用字符串的format()方法,它会用传入的参数依次替换字符串内的占位符{0}{1}……,不过这种方式写起来比%要麻烦得多:

  1. # 最简单的情况下,替换字段没有名称或将索引用做名称。
  2. >>> '{}, {} and {}'.format('first', 'second', 'thrid')
  3. 'first, second and third'
  4. >>> '{0}, {1} and {2}'.format('first', 'second', 'third')
  5. >>> 'first, second and third'
  6. # 索引也可不按顺序排列
  7. >>> '{3} {0} {2} {1} {3} {0}'.format('be', 'not', 'or', 'to')
  8. 'to be or not to be'
  9. # 命名字段
  10. >>> from math import pi
  11. >>> '{name} is approximately {value:.2f}'.format(value=pi, name='π')
  12. 'π is approximately 3.14.'
  13. # 混合使用未命名参数或索引指定,和命名字段
  14. >>> '{foo} {} {bar} {}'.format(1,2,bar=4,foo=3)
  15. '3 1 4 2'
  16. >>> '{foo} {1} {bar} {0}'.format(1,2,bar=4,foo=3)
  17. '3 2 4 1'
  18. # 不能同时使用手工编号和自动编号,因为这样很快会变得混乱不堪。
  19. >>> fullname = ["Alfred", "Smoketoomuch"]
  20. >>> "Mr {name[1]}".format(name=fullname)

宽度、精度和千位分隔符

  1. # 宽度是使用整数指定的,如下所示:
  2. >>> "{num:10}".format(num=3)
  3. ' 3'
  4. >>> "{name:10}".format(name="Bob")
  5. 'Bob '
  6. # 数和字符串的对齐方式不同

f-string

在Python 3.6中,如果变量与替换字段同名,可使用f字符串——在字符串前面加上f。以f开头的字符串,字符串如果包含{xxx},就会以对应的变量替换:

  1. >>> r = 2.5
  2. >>> s = 3.14 * r **2
  3. >> print(f'The area of a circle with radius {r} is {s:.2f}')
  4. The area of a circle with radius 2.5 is 19.62

字符串方法

center

通过在两边添加填充字符(默认为空格)让字符串居中。

  1. >>> "The Middle by Jimmy Eat World".center(39)
  2. ' The Middle by Jimmy Eat World '
  3. >>> "The Middle by Jimmy Eat World".center(39, '*')
  4. '*****The Middle by Jimmy Eat World*****'

相关方法: ljustrjustzfill

find

在字符串中查找子串。如果找到就返回子串的第一个字符的索引,否则返回-1。

  1. >>> 'With a moo-moo here, and a moo-moo there'.find('moo')
  2. 7
  3. >>> title = "Monty Python's Flying Circus"
  4. >>> title.find('Monty')
  5. 0
  6. >>> title.find('Zirquss')
  7. -1

还可指定搜索的起点和终点。

  1. >>> subject = '$$$ Get rich now!!! $$$'
  2. >>> subject.find('$$$')
  3. 0
  4. >>> subject.find('$$$', 1) # 只指定了起点
  5. 20
  6. >>> subject.find('!!!', 0, 16) # 同时指定了起点和终点
  7. -1

注意: 起点和终点指定的搜索范围包含起点,但不包含终点。这是Python惯常的做法。

相关方法: rfindindexrindexcountstartswithendswith

join

合并序列的元素。

  1. >>> seq = ['1','2','3','4','5']
  2. >>> sep = '+'
  3. >>> sep.join(seq) # 尝试合并一个字符串列表
  4. '1+2+3+4+5'
  5. >>> dirs = '', 'usr', 'bin', 'env'
  6. >>> '/'.join(dirs)
  7. '/usr/bin/env'

相关方法: split

lower

返回字符串的小写版本。

  1. >>> 'Trondheim Hammer Dance'.lower()
  2. 'trondheim hammer dance'

相关方法: isloweristitleisuppertranslate
capitalizecasefoldseapcasetitleupper

replace

将指定子串都替换为另一个字符串,并返回替换后的结果

  1. >>> 'This is test'.replace('is', 'eez')
  2. 'Theez eez a test'

相关方法:translateexpandtabs

split

作用与join相反,用于将字符串拆分为序列。

  1. '1+2+3+4+5'.split('+')
  2. ['1','2','3','4','5']
  3. >>> 'Using the default'.split()
  4. ['Using', 'the', 'default']

如果没有指定分隔符,将默认在单个或多个连续的空白字符处进行拆分。

相关方法:joinpartitionrpartitionrsplitsplitlines

strip

将字符串开头和末尾的空白删除,并返回删除后的结果。

  1. >>> ' internal whitespace is kept '.strip()
  2. 'internal whitespace is kept'

还可以在一个字符串参数中指定要删除哪些字符。

  1. '*** SPAM * for * everyone!!! ***'.strip(' *!')
  2. 'SPAM * for *evenyone'

相关方法: lstriprstrip

translate

与replace一样替换字符串的特定部分,但不同的是它只能进行单字符替换。
优势在于能够同时替换多个字符,因此效率比replace高。
使用translate前必须创建一个转换表。这个转换表指出了不同Unicode码点之间的转
换关系。要创建转换表,可对字符串类型str调用方法maketrans,这个方法接受两个参数:两个长度相同的字符串,它们指定要将第一个字符串中的每个字符都替换为第二个字符串中的相应字符。

  1. >>> table = str.maketrans('cs', 'kz')
  2. >>> table
  3. {115: 122, 99: 107}

创建转换表后,就可将其用作方法translate的参数。

  1. >>> 'this is an incredible test'.translate(table)
  2. 'thiz iz an inkredible tezt'
  3. # 第三个参数(可选),指定要将哪些字母删除。
  4. >>> table = str.maketrans('cs', 'kz', ' ')
  5. >>> 'this is an incredible test'.translate(table)
  6. 'thizizaninkredibletezt'

相关方法: replacelower

判断字符串是否满足特定的条件

很多字符串方法都以is打头,如isspace、isdigit和isupper,它们判断字符串是否具特定的性质(如包含的字符全为空白、数字或大写)。如果字符串具备特定的性质,这些方法就返回True,否则返回False。
附录B:isalnumisalphaisdecimalisdigitisidentifierislowerisnumericisprintableisspaceistitleisupper