https://docs.python.org/3/library/stdtypes.html#str
字符串相关函数
'capitalize', (首字母大写,其余转小写)
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
长度
len(str)
ascii 互转
chr(123)
Out[68]: '{'
ord('1')
Out[72]: 49
字符串匹配
# 1. in 返回 True 或者 False (效率最高)
In [76]: '123' in stra
Out[76]: False
In [77]: 'cd' in stra
Out[77]: True
# 2. index 、 rindex , 查不到返回异常 ,查询到返回从0开始的位置
# index(sub, start,end)
In [78]: stra.index('123')
Traceback (most recent call last):
File "", line 1, in
stra.index('123')
ValueError: substring not found
In [80]: stra.index('cd')
Out[80]: 2
In [81]: stra.index('cd',1)
Out[81]: 2
In [87]: stra.rindex('cd',1,4)
Out[87]: 2
# 3. find 、 rfind , 查询不到返回-1 ,返回从0开始的位置
In [88]: stra.find('cd')
Out[88]: 2
In [89]: stra.find('cd',1,2)
Out[89]: -1
In [90]: stra.rfind('cd')
Out[90]: 2
In [91]: stra.rfind('cd',2,3)
Out[91]: -1
# 4. startswith 、 endswith , 以xx开头或结尾,返回True 、False
In [100]: stra.startswith('123')
Out[100]: False
In [101]: stra.endswith('123')
Out[101]: False
In [102]: stra.startswith('abc')
Out[102]: True
分割 https://docs.python.org/3/library/stdtypes.html#str.split
split(sep=None, maxsplit=-1) , 返回一个list 。
maxsplit 表示分割的次数, 默认-1不限制分割次数,当使用了该参数,则列表中至多有maxsplit+1个元素。
sep默认为None ,将按空白分割,此时对于字符串行首和行尾的字符串会trip掉。 当字符串由空白字符组成时, 会返回[] .
In [111]: t2 = ' no empty strings at '
In [112]: t2.split()
Out[112]: ['no', 'empty', 'strings', 'at']
In [113]: t3 = ' \t \n '
In [114]: t3
Out[114]: ' \t \n '
In [115]: t3.split()
Out[115]: []
splitlines([keepends]) 按换行符分割成列表 , 若keepends= True , 则换行符会作为列表中的元素 。
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
连接
In [128]: stra
Out[128]: 'abcdefg'
In [129]: stra.join(['1','33','44','66'])
Out[129]: '1abcdefg33abcdefg44abcdefg66'
截取
In [123]: stra[1:3]
Out[123]: 'bc'
字符串转数字
In [133]: int(a)
Out[133]: 123
In [134]: int('12a')
Traceback (most recent call last):
File "", line 1, in
int('12a')
ValueError: invalid literal for int() with base 10: '12a'
In [135]: str(123)
Out[135]: '123'
In [136]: str(38.5)
Out[136]: '38.5'
数字进制转换
In [142]: bin(c)
Out[142]: '0b100110'
In [143]: oct(c)
Out[143]: '0o46'
In [144]: hex(c)
Out[144]: '0x26'
In [145]: int('100110',2)
Out[145]: 38
In [147]: int('46',8)
Out[147]: 38
In [149]: int('26' , 16)
Out[149]: 38