所有的标准序列操作(索引、切片、相乘、成员资格检查、长度、最大和最小值)都适用于字符串。
但字符串是不可变的,因此所有的元素赋值和切片赋值都是非法的。
字符串方法
字符串的很多方法是从模块string“继承”而来的,这里仅介绍一些最有用的。
1、center
方法center通过在两边添加填充字符(默认为空格)让字符串居中。
>>> str = "Hello, Python!"
>>> str.center(20)
' Hello, Python! '
>>> str.center(20, "*")
'***Hello, Python!***'
2、find
方法find在字符串中查找子字符串。
如果找到则返回子字符串的第一个字符的索引,否则返回-1。
>>> str = "Hello, Python!"
>>> str.find('Hello')
0
>>> str.find('Python')
7
>>> str.find('python')
-1
可以指定搜索的起点和重点(都是可选参数)。
>>> str = "*** Hello, Python! ***"
>>> str.find('***', 1)
19
>>> str.find('***', 1, 19)
-1
注意:搜索范围包含起点,但并不包含重点。
3、join
join是一个非常重要的字符串方法,用于合并序列的元素。
>>> lst = ['1', '2', '3', '4', '5']
>>> sep = '+'
>>> sep.join(lst)
'1+2+3+4+5'
所合并序列的元素必须是字符串。
>>> lst = [1, 2, 3, 4, 5]
>>> sep.join(lst)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
这里要注意序列是参数,而不是调用方。
4、split
split是一个非常重要的字符串方法,作用与join相反,用于将字符串拆分为序列。
>>> str = '1+2+3+4+5'
>>> str.split('+')
['1', '2', '3', '4', '5']
如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格、制表符、换行符等)处进行拆分。
>>> str = '1 2 3 4 5'
>>> str.split()
['1', '2', '3', '4', '5']
5、strip
方法strip将字符串开头和末尾的空白或者指定字符删除,并返回删除后的结果。
>>> str = ' This is python. '
>>> str.strip()
'This is python.'
也可以指定要删除哪些字符。
>>> str = '*** This is python.!!! ***'
>>> str.strip(' *!')
'This is python.'
6、replace
方法replace将指定子字符串都替换为另一个字符串,并返回替换后的结果。
>>> str = "Hello, Python!"
>>> str.replace('Python', 'World')
'Hello, World!'
7、translate
方法translate与replace一样都能替换字符串的特定部分,但不同的是它只能进行单字符替换。
这个方法的优势在于能够同时替换多个字符,因此效率比replace高。
在使用translate前必须创建一个转换表。转换表指出了字符替换的对应关系。比如要把字符串中的所有'o'字符替换为'x'字符:
table = str.maketrans('o', 'x')
创建转换表后,就可将其用作方法translate的参数。
>>> s = 'Hello, Python!'
>>> table = str.maketrans('o', 'x')
>>> s.translate(table)
'Hellx, Pythxn!'
如果想同时替换'o'字符和'H'字符,那么可以这么操作:
>>> s = 'Hello, Python!'
>>> table = str.maketrans('Ho', 'Jx')
>>> s.translate(table)
'Jellx, Pythxn!'
调用方法maketrans时,还可提供可选的第三个参数,指定要将哪些字母删除。
>>> s = 'Hello, Python!'
>>> table = str.maketrans('Ho', 'Jx', 'l')
>>> s.translate(table)
'Jex, Pythxn!'
8、lower
方法lower返回字符串的小写版本。
'Hello, Python!'.lower()
'hello, python!'
同类操作:upper、title、swapcase、capitalize等。
9、字符串条件判断
string.isalnum() 判断字符串中的字符是否都是字母或数
string.isalpha() 判断字符串中的字符是否都是字母
string.isdigit() 判断字符串中的字符是否都是数字
string.isnumeric() 判断字符串中的所有字符是否都是数字字符
string.islower() 判断字符串中的所有字母是否都是小写的
string.isupper() 判断字符串中的所有字母是否都是大写的
string.isspace() 判断字符串中的字符是否都是空白字符
string.isprintable() 判断字符串中的字符是否都是可打印的
string.isdecimal() 判断字符串中的字符是否十进制数
string.isidentifier() 判断字符串是否可用作Python标识符