使用字符串
1 字符串基本操作
所有标准序列操作(索引、切片、乘法、成员资格检查、长度、最小值和最大值)都适用于字符串。字符串是不可变的,所以无法赋值。
>>> website = 'http://www.python.org'
>>> website[-3:] = 'com'
Traceback (most recent call last):
File "<pyshell#19>", line 1, in ?
website[-3:] = 'com'
TypeError: object doesn't support slice assignment
2 设置字符串的格式:精简版
>>> format = "Hello, s. s enough for ya?" % %
>>> values = ('world', 'Hot')
>>> format values %
'Hello, world. Hot enough for ya?'
上述格式字符串中的 s % 称为转换说明符,指出了要将值插入什么地方。 s 意味着将值视为字符串进行格式设置。如果指定的值不是字符串,将使用 str 将其转换为字符串。
字符串方法 format,将format后面的参数填入前面的“{}”
>>> "{}, {} and {}".format("first", "second", "third")
'first, second and third'
>>> "{0}, {1} and {2}".format("first", "second", "third")
'first, second and third'
3 设置字符串的格式:完整版
这里的基本思想是对字符串调用方法 format,并提供要设置其格式的值。
替换字段名
未命名参数按顺序放入“{}”,给参数指定名称后按名称放入
>>> "{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'
基本转换
可以提供一个转换标志。
s 、 r 和 a 指定分别使用 str 、 repr 和 ascii 进行转换。函数 str 通常创建外观普通的字符串版本(这里没有对输入字符串做任何处理)。函数 repr 尝试创建给定值的Python表示(这里是一个字符串字面量)。函数 ascii 创建只包含ASCII字符的表示
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
π 'π' '\u03c0'
宽度、精度
宽度是使用整数指定的,如下所示:
>>> "{num:10}".format(num=3)
' 3'
>>> "{name:10}".format(name="Bob")
'Bob '
精度也是使用整数指定的,但需要在它前面加上一个表示小数点的句点。
>>> "Pi day is {pi:.2f}".format(pi=pi)
'Pi day is 3.14'
可同时指定宽度和精度。
>>> "{pi:10.2f}".format(pi=pi)
' 3.14'
4 字符串方法
center
方法 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*****'
find
方法 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
join
join 是一个非常重要的字符串方法,其作用与 split 相反,用于合并序列的元素。
>>> seq = [1, 2, 3, 4, 5]
>>> sep = '+'
>>> sep.join(seq) # 尝试合并一个数字列表
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: sequence item 0: expected string, int found
>>> seq = ['1', '2', '3', '4', '5']
>>> sep.join(seq) # 合并一个字符串列表
'1+2+3+4+5'
>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print('C:' + '\\'.join(dirs))
C:\usr\bin\env
lower
方法 lower 返回字符串的小写版本。
>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'
replace
方法 replace 将指定子串都替换为另一个字符串,并返回替换后的结果。
>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'
split
split 作用与 join 相反,用于将字符串拆分为序列。
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 'Using the default'.split()
['Using', 'the', 'default']
strip
方法 strip 将字符串开头和末尾的空白(删除,并返回删除后的结果。
>>> ' internal whitespace is kept '.strip()
'internal whitespace is kept'
translate
方法 translate 与 replace 一样替换字符串的特定部分,但不同的是它只能进行单字符替换
指定要将第一个字符串中的每个字符都替换为第二个字符串中的相应字符,创建转换表后,就可将其用作方法 translate 的参数。
>>> table = str.maketrans('cs', 'kz')
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'