1、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*****'
2、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
>>> title.find('Python')
6
>>> title.find('Flying')
15
>>> title.find('Zirquss')
-1
3、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
4、lower
方法lower返回字符串的小写版本。
>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'
5、replace
方法replace将指定子串都替换为另一个字符串,并返回替换后的结果。
>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'
6、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']
7、strip
方法strip将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果。
>>> ' internal whitespace is kept '.strip()
'internal whitespace is kept'
8、isspace、isdigit和isupper等等以is开头的方法
它们判断字符串是否具有特定的性质(如包含的字符全为空白、数字或大写)。
如果字符串具备特定的性质,这些方法就返回
True,否则返回False。

1121

被折叠的 条评论
为什么被折叠?



