引自:https://segmentfault.com/a/1190000004598007?_ea=663877#articleHeader7
概览
字符串大小写转换
- str.capitalize() #将首字母转换成大写,需要注意的是如果首字没有大写形式,则返回原字符串。

1 >>> 'root '.capitalize() 2 'Root ' 3 >>> 'root ubuntu'.capitalize() 4 'Root ubuntu' 5 >>> '王root ubuntu'.capitalize() 6 '王root ubuntu'
- str.lower() # 将字符串转换成小写,其仅对
ASCII
编码的字母有效。

1 # 'ß' 为德语小写字母,其有另一种小写 'ss', lower 方法无法转换
- str.casefold()

1 >>> 'UBUNTU'.casefold() 2 'ubuntu' 3 >>> 'ß'.casefold() 4 'ss' 5 >>> '海'.casefold() 6 '海'
- str.swapcase()

1 >>> '徐Dobi a123 ß'.swapcase() 2 '徐dOBI A123 SS'
- str.title()

1 >>> 'Hello world'.title() 2 'Hello World' 3 >>> '中文abc def 12gh'.title() 4 '中文Abc Def 12Gh' 5 >>> # 但这个方法并不完美: 6 ... "they're bill's friends from the UK".title() 7 "They'Re Bill'S Friends From The Uk"
- str.upper()

1 >>> '中文abc def 12gh'.upper() 2 '中文ABC DEF 12GH'
字符串格式输出
- str.center(width[, fillchar])

1 >>> '12345'.center(10, '*') 2 '**12345***' 3 >>> '12345'.center(10) 4 ' 12345 '
- str.ljust(width[, fillchar]); str.rjust(width[, fillchar])

1 >>> 'dobi'.ljust(10) 2 'dobi ' 3 >>> 'dobi'.ljust(10, '~') 4 'dobi~~~~~~' 5 >>> 'dobi'.ljust(3, '~') 6 'dobi' 7 >>> 'dobi'.ljust(3) 8 'dobi'
- str.zfill(width)

1 >>> "42".zfill(5) 2 '00042' 3 >>> "-42".zfill(5) 4 '-0042' 5 >>> 'dd'.zfill(5) 6 '000dd' 7 >>> '--'.zfill(5) 8 '-000-' 9 >>> ' '.zfill(5) 10 '0000 ' 11 >>> ''.zfill(5) 12 '00000' 13 >>> 'dddddddd'.zfill(5) 14 'dddddddd'
- str.expandtabs(tabsize=8)

1 >>> tab = '1\t23\t456\t7890\t1112131415\t161718192021' 2 >>> tab.expandtabs() 3 '1 23 456 7890 1112131415 161718192021' 4 >>> tab.expandtabs(4) 5 '1 23 456 7890 1112131415 161718192021' 6 >>> print(tab) 7 1 23 456 7890 1112131415 161718192021
- str.format(^args, ^^kwargs)
- str.format_map(mapping)

1 >>> People = {'name':'john', 'age':56} 2 >>> 'My name is {name},i am {age} old'.format_map(People) 3 'My name is john,i am 56 old'
字符串搜索定位与替换
- str.count(sub[, start[, end]])

1 >>> text = 'outer protective covering' 2 >>> text.count('e') 3 4 4 >>> text.count('e', 5, 11) 5 1 6 >>> text.count('e', 5, 10) 7 0
-
str.find(sub[, start[, end]]); str.rfind(sub[, start[, end]])

1 >>> text = 'outer protective covering' 2 >>> text.find('er') 3 3 4 >>> text.find('to') 5 -1 6 >>> text.find('er', 3) 7 3 8 >>> text.find('er', 4) 9 20 10 >>> text.find('er', 4, 21) 11 -1 12 >>> text.rfind('er') 13 20
-
str.index(sub[, start[, end]]); str.rindex(sub[, start[, end]])

1 >>> text = 'outer protective covering' 2 >>> text.index('er') 3 3 4 >>> text.index('eraa') 5 Traceback (most recent call last): 6 File "<stdin>", line 1, in <module> 7 ValueError: substring not found
-
str.replace(old, new[, count])

1 >>> 'dog wow wow jiao'.replace('wow', 'wang', 1) 2 'dog wang wow jiao'
-
str.lstrip([chars]); str.rstrip([chars]); str.strip([chars])

1 >>> s = " For you, a thousand times over. " 2 >>> s.strip() # 移除俩端空白 3 'For you, a thousand times over.' 4 >>> s.lstrip() #移除左边空白 5 'For you, a thousand times over. ' 6 >>> s.rstrip() #移除右边空白 7 ' For you, a thousand times over.'
# 先注掉 static str.maketrans(x[, y[, z]]); str.translate(table)
字符串的联合与分割
-
str.join(iterable)

1 >>> '-'.join(['2012', '3', '12']) 2 '2012-3-12' 3 >>> '-'.join([2012, 3, 12]) 4 Traceback (most recent call last): 5 File "<stdin>", line 1, in <module> 6 TypeError: sequence item 0: expected str instance, int found 7 >>> ','.join({'dobi':'dog', 'polly':'bird'}) 8 'dobi,polly' 9 >>> ','.join({'dobi':'dog', 'polly':'bird'}.values()) 10 'dog,bird'
-
str.partition(sep); str.rpartition(sep)

1 >>> 'dog wow wow jiao'.partition('wow') 2 ('dog ', 'wow', ' wow jiao') 3 >>> 'dog wow wow jiao'.partition('dog') 4 ('', 'dog', ' wow wow jiao') 5 >>> 'dog wow wow jiao'.rpartition('wow') 6 ('dog wow ', 'wow', ' jiao')
-
str.split(sep=None, maxsplit=-1); str.rsplit(sep=None, maxsplit=-1)

1 >>> '1,2,3'.split(','), '1, 2, 3'.rsplit() 2 (['1', '2', '3'], ['1,', '2,', '3']) 3 >>> '1,2,3'.split(',', maxsplit=1), '1,2,3'.rsplit(',', maxsplit=1) 4 (['1', '2,3'], ['1,2', '3']) 5 >>> ''.split() 6 [] 7 >>> ''.split('a') 8 ['']
# str.splitlines([keepends])
字符串条件判断
-
str.endswith(suffix[, start[, end]]); str.startswith(prefix[, start[, end]])
以什么开始、什么结束
- str.isalnum()
字符串和数字的任意组合,即为真。
>>> 'hello assss22'.isalnum()
False
>>> 'helloassss22'.isalnum()
True
#str.isalpha()
-
str.isdecimal(); str.isdigit(); str.isnumeric()
isdecimal() 方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。
isdigit() 方法用于判断指定字符是否为数字。
isnumeric() 方法检测字符串是否只由数字组成。这种方法是只针对unicode对象。
- str.isidentifier()

1 >>> 'def'.isidentifier() 2 True 3 >>> 'with'.isidentifier() 4 True 5 >>> 'with.'.isidentifier() 6 False 7 >>> 'dobi_123'.isidentifier() 8 True 9 >>> '2dobi_123'.isidentifier() 10 False 11 >>> '_2dobi_123'.isidentifier() 12 True
- str.islower()

1 >>> '徐'.islower() 2 False 3 >>> '王'.islower() 4 False 5 >>> 'ss'.islower() 6 True 7 >>> 'Ab'.islower() 8 False 9 >>> '23'.islower() 10 False 11 >>> 'a王'.islower() 12 True
- str.isprintable()

1 >>> 'dobi123'.isprintable() 2 True 3 >>> 'dobi123\n'.isprintable() 4 False 5 >>> 'dobi 123'.isprintable() 6 True 7 >>> ''.isprintable() 8 True
- str.isspace()

1 >>> '\r\n\t'.isspace() 2 True 3 >>> ''.isspace() 4 File "<stdin>", line 1 5 ''.isspace() 6 ^ 7 IndentationError: unexpected indent 8 >>> ' '.isspace() 9 File "<stdin>", line 1 10 ' '.isspace() 11 ^ 12 IndentationError: unexpected indent
- str.istitle()

1 >>> 'How Python Works'.istitle() 2 True 3 >>> 'How Python WORKS'.istitle() 4 False 5 >>> ' '.istitle() 6 False
- str.isupper()

1 >>> '徐'.isupper() 2 False 3 >>> 'A徐'.isupper() 4 True 5 >>> 'Dobi'.isupper() 6 False 7 >>> 'DOBI\t 123'.isupper() 8 True
字符串编码
- str.encode(encoding="utf-8", errors="strict")
Python encode() 方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。