字符串方法
字符串(str)在Python中是一个对象(object),并且包含很多的方法(method),这些方法可以给我们操作字符串带来很大的方便,下面列举一些常用的方法及使用示例。
- str.capitalize()
把字符串的首字母转为大写
>>> 'hello'.capitalize()
'Hello'
- str.lower()
把字符串转换为小写
>>> 'Hello'.lower()
'hello'
- str.upper()
把字符串转换为大写
>>> 'Hello'.upper()
'HELLO'
- str.center(width[,fillchar])
返回一个长度为width,原始字符串居中,两边多余长度使用fillchar填充的字符串
>>> 'abc'.center(10, '=')
'===abc==='
>>> 'abc'.center(10) # fillchar默认为空格
' abc '
>>> 'abc'.center(3) # 如果width小于等于字符串长度,则返回原始字符串
'abc'
- str.count(sub[,start[, end]])
在字符串的start到end范围内查找字符串sub出现的次数
start默认为0,end默认为字符串长度,即默认查找整个字符串
>>> 'abcad'.count('a')
2
>>> 'abcad'.count('a', 0, 3)
1
>>> 'abcad'.count('a', 0, 4)
2
- str.encode(encoding=‘utf-8’, errors=‘strict’)
对字符串按照encoding进行编码
>>> '中文'.encode()
b'\xe4\xb8\xad\xe6\x96\x87'
- str.startswith(prefix[, start[, end]])
判断字符串在start到end范围内是否以prefix开头,是返回True,否则返回False
prefix可以是多个,以tuple格式传入
str.endswith方法与此方法类似
>>> 'abc'.startswith('a')
True
>>> 'abc'.startswith('b')
False
>>> 'abc'.startswith(('a', 'b')) # 是否以'a'或'b'开头
True
- str.find
在字符串的start到end范围内查找子字符串sub,如果查到则返回sub出现的最小起始索引号,否则返回-1
>>> 'abcdbf'.find('b')
1
>>> 'abcdbf'.find('x')
-1
如果只需要判断是否包含子字符串,可以使用in关键字进行判断,无需使用find
>>> 'b' in 'abc'
True
>>> 'd' in 'abc'
False
- str.index
与str.find方法类似,不用的是如果没有查找到子字符串sub,会抛出ValueError异常
>>> 'abcdbf'.index('b')
1
>>> 'abcdbf'.index('x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
- str.format(*args, **kwargs)
格式化字符串,此方法在下面会进行详细讲解,这里只演示一个简单的示例
>>> 'The sum of 1 +2 is {0}'.format(1+2)
'The sum of 1 +2 is 3'
- str.join(iterable)
把iterable中的字符串元素用str进行连接
iterable可以是list、tuple等可迭代对象,但是里边的元素必须是str类型
>>> '_'.join(['a', 'b', 'c'])
'a_b_c'
>>> '_'.join([1, 2, 3]) # 不能是非str类型
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
- str.strip([chars])
-去除字符串首尾在chars中出现的字符
如果chars不指定,则默认去除空白字符
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
- str.lstrip([chars])
只去除左边(首部)的字符
>>> ' spacious '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
-
str.rstrip([chars])
与lstrip类似,只是去除右边(尾部)的字符 -
str.split(sep=None, maxsplit=-1)
用分隔符sep对字符串进行最多maxsplit次切割,返回切割后的list
sep默认为空白字符,即空格、制表符等
maxsplit如果不指定或指定为-1,则会进行最大次数的切割
# 指定sep
>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',',maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']
# 不指定 sep
>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> ' 1 2 3 '.split()
['1', '2', '3']
- str.splitlines([keepends])
把字符串按照行为边界符(line boundaries)切割成多行,并以list形式返回
如果keepends为True,则返回的每行末尾仍然包含换行符,keepends默认为False
>>> 'first line \nsecond line \r\nthird line'.splitlines()
['first line ', 'second line ', 'third line']
>>> 'first line \nsecond line \r\nthird line'.splitlines(True)
['first line \n', 'second line \r\n', 'third line']