python 字符串内未知字符匹配 python字符串内置方法_Python

 编码相关内置方法:

(1)    str.encode(encoding='utf-8'):返回字符串编码,encoding指定编码方式。
>>> a = 'I love Python'
>>> a.encode(encoding='utf-8')
b'I love Python'
>>> a.encode(encoding='gbk')
b'I love Python'
>>> b.encode(encoding='utf-8')
b'\xe6\x88\x91\xe7\x88\xb1 Python'
>>> b.encode(encoding ='gbk')
b'\xce\xd2\xb0\xae Python'

 替换相关内置方法:

(1)     str.expandtabs(tabsize=8) 把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8.'abc\tcdg' \t就会被替换
>>> a = 'Here is the tab \t key'
>>> a
'Here is the tab \t key'
>>> print(a)
Here is the tab          key
>>> a.expandtabs(tabsize=40)
'Here is the tab                          key'
>>> print(a.expandtabs(tabsize=40))
Here is the tab                          key
(2)     str.replace(str1, str2,  num=string.count(str1))  返回一个新的字符串,把 string 中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次.
>>> a = 'Puppy is a little dog, she is a cute dog'
>>> a.replace('dog','cat')
'Puppy is a little cat, she is a cute cat'
>>> a.replace('dog','cat',1)
'Puppy is a little cat, she is a cute dog'
(3)     str.maketrans() 和str.translate()联合使用。
maktrans 是一个静态方法,用于生成一个对照表,以供 translate 使用。
有两种定义tanslatetable的方法,
第一种方法是传入参数,前两个会自动生成单个字母一一对应的关系,所以这两个的长度应该相同,若有第三个参数,那么它自动对应None。
 >>> trans_table = str.maketrans('here','bist')
>>> a.translate(trans_table)
'btst ast codts'
>>> a
'here are codes'
第二种生成对照表的方法就是生成一个字典,但是字典的key的length一定要是1.
>>> trans_table = str.maketrans({'a':'hehe','r':'haha','e':'dede'})
>>> a.translate(trans_table)
'hdedehahadede hehehahadede coddedes'

大小写类内置方法:

(1)     str.capitalize():返回新字符串,把str第一个字符大写。
(2)     str.upper():返回新字符串,把str所有字符大写。
(3)     str.title():返回新字符串,每个单词首字符大写。
>>> a = "here are codes"
>>> a.capitalize()
'Here are codes'
>>> a.title()
'Here Are Codes'
>>> a.upper()
'HERE ARE CODES'
(4)     str.lower():返回新字符串,把str所有字符小写。
(5)     str.casefold():和lower()类似,用于转小语种比如德语一些字符大小写转换。中英文还是用lower()
(6)     str.swapcase():返回新字符串,所有字符大小写互换。
>>> c = "Here aRe CoDE"
>>> a.lower()
'here are codes'
>>> c.swapcase()
'hERE ArE cOde'

 查找类内置方法:

(1)     str.find(substr,beg=0,end=len(str)):查找str中是否有substr,如果有,返回查到的第一个index,如果没有返回-1.查找的开始位置和结束为止可指定。
(2)     str.rfind(substr,beg=0,end=len(str)):同find,只是从右边开始找。
>>> a = 'I have a dream, I will be good at Python'
>>> a.find('a')   #找到返回索引值
3
>>> a.rfind('a')
31
>>> a.find('a',7,12)
7
>>> a.find('a',8,12)  # 找不到返回-1
-1
>>> a.find('a',8,13)  #说明查找范围包括beg,不包括end的位置。左闭右开的。
12
>>> len(a)
40
>>> a.rfind('a',39,30)  # 说明即使从右边查找这个查找范围,还是beg <end
-1
>>> a.rfind('a',30,39)
31
 
(3)     str.index(substr,beg=0,end=len(str)):同find,只是,如果没有找到,返回异常。
(4)     str.rindex(substr,beg=0,end=len(str)):同index,从右边开始找
>>> a.index('a')
3
>>> a.rindex('a')
31
>>> a.index('a',7,12)
7
>>> a.index('a',8,12)    #查不到返回异常ValueError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> a.index('a',8,13)
12
>>> a.rindex('a',39,30)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> a.rindex('a',30,39)
31
>>> 
(5)     str.count(substr,beg=0,end=len(str)):str中substr出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
>>> a
'I have a dream, I will be good at Python'
>>> a.count('a')
4
>>> a.count('a',0,12)   #位置依然是左闭右开
2

字符串拼接,分隔类方法

(1)     str.join(sequence):把sequence序列中的元素,用str连接起来。
>>> seq = ['Dog','is','so','cute']
>>> '-'.join(seq)
'Dog-is-so-cute'
(2)     str.split(substr="", num=string.count(str))  返回一个列表,列表元素是以 substr 为分隔符切片 str,如果 num有指定值,则仅分隔 num 个子字符串,分割后substr不保留
>>> ff = 'I have a dream, I will be good at Python'
>>> ff.split('a')
['I h', 've ', ' dre', 'm, I will be good ', 't Python']
>>> ff.split('a',3)
['I h', 've ', ' dre', 'm, I will be good at Python']
(3)     str.rsplit(substr="", num=string.count(str))  同split,从str右边开始。
>>> ff.rsplit('a')   #在num数就是substr个数时和split的结果一样
['I h', 've ', ' dre', 'm, I will be good ', 't Python']
>>> ff.rsplit('a',3)
['I have ', ' dre', 'm, I will be good ', 't Python']
(4)     str.splitlines(num=str.count('\n')) 按照行分隔,返回一个包含各行作为元素的列表,如果 num 指定则仅切片 num 个行.
>>> ff = 'I have a dream,\nI will be good at Python'
>>> ff
'I have a dream,\nI will be good at Python'
>>> print(ff)
I have a dream,
I will be good at Python
>>> ff.splitlines()
['I have a dream,', 'I will be good at Python']
>>> ff.splitlines(keepends=True)
['I have a dream,\n', 'I will be good at Python']
(5)     str.partition(substr)  用substr把一个str分成三段,返回一个三个字符串组成的列表,分割后seperator作为一个列表元素保留。
(6)     str.rpartition(substr)  用substr把一个str分成三段,返回一个三个字符串组成的列表,从右边开始分。
>>> ff
'I have a dream,\nI will be good at Python'
>>> ff.partition('\n')
('I have a dream,', '\n', 'I will be good at Python')
>>> ff.partition('a')   #‘a’’有多个,以第一个‘a’分隔
('I h', 'a', 've a dream,\nI will be good at Python')
>>> ff.partition('m')
('I have a drea', 'm', ',\nI will be good at Python')
>>> ff.rpartition('a')
('I have a dream,\nI will be good ', 'a', 't Python')

 字符串去掉空格方法:

(1)     str.lstrip():返回截掉字符串左边空格的新字符串
(2)     str.rstrip():返回截掉字符串右边空格的新字符串
(3)     str.strip():返回截掉字符串两边空格的新字符串
>>> a = '    here are codes    '
>>> a.strip()
'here are codes'
>>> a.lstrip()
'here are codes    '
>>> a.rstrip()
'    here are codes'

 字符串对齐类方法:

(4)     str.center(width):返回指定长度的新字符串,原字符串居中,不足填充空格。
(5)     str.ljust(width):返回指定长度的新字符串,原字符串左对齐,不足填充空格
(6)     str.rjust(width):返回指定长度的新字符串,原字符串右对齐,不足填充空格。
(7)     str.zfill(width):返回指定长度的新字符串,原字符串右对齐,不足填充0。
>>> a ='here are codes'
>>> a.center(30)
'        here are codes        '
>>> a.center(30,'+')
'++++++++here are codes++++++++'
>>> a.ljust(30,'+')
'here are codes++++++++++++++++'
>>> a.rjust(30,'+')
'++++++++++++++++here are codes'
>>> a.zfill(30)
'0000000000000000here are codes'

字符串各种判断方法:

(1)     str.endswith(obj, beg=0, end=len(str)) 检查字符串是否是以 obj 结束,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查.
(2)     str.startswith(obj, beg=0, end=len(str)) 检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查
>>> a
'here are codes'
>>> a.startswith('he')
True
>>> a.startswith('be')
False
>>> a.endswith('be')
False
>>> a.endswith('es')
True
(3)     str.isalnum() 如果 str至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
(4)     str.isalpha() 如果 str至少有一个字符并且所有字符都是字母则返回 True,否则返回 False
(5)     str.isdecimal() 如果 str 只包含十进制数字则返回 True 否则返回 False
(6)     str.isdigit() 如果 str 只包含数字则返回 True 否则返回 False.
(7)     str.isnumeric() 如果 string 中只包含数字字符,则返回 True,否则返回 False。字符串中是只包含数字,isdigit更为强大,isnumeric还可识别中文 '12345二',isnumeric判断为True,其他判断为False
>>> a = 'sdf1878er'
>>> b = '684050'
>>> c = 'abd567'
>>> d = '0x76ed'
>>> a.isalnum()
True
>>> a.isalpha()
False
>>> a.isdecimal()
False
>>> b.isdecimal()
True
>>> b.isdigit()
True
>>> c.isdigit()
False
>>> e.isnumeric()
True
>>> e.isdigit()
False
>>> e.isdecimal()
False
(8)     str.islower()  如果 str 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
(9)     str.isupper()  如果 str 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
>>> a = 'effadf'
>>> b = 'DFGTYH'
>>> c = 'efHedH'
>>> a.islower()
True
>>> b.isupper()
True
>>> c.islower()
False
>>> c.isupper()
False
(10)  str.isspace()  如果 string 中只包含空格,则返回 True,否则返回 False。
>>> a = '  I love python '
>>> a.isspace()
False
>>> b = '    '
>>> b.isspace()
True
(11)  str.istitle()  如果 string 是标题化的(见 title())则返回 True,否则返回 False
>>> a = '   I Love Python  '
>>> a.istitle()    #不看空格
True
>>> a = 'I love python'
>>> a.istitle()
False
(12)  str.isprintable() str中是否都是可打印的字符,如果有'abc\t' return False
>>> a = 'I\tlovePython'
>>> a.isprintable()
False
>>> a = 'Ilove\nPython'
>>> a.isprintable()
False
>>> a = 'I love python   '
>>> a.isprintable()
True
(13)  str.isidentifier() 判断字符串是够包含该语言的保留字
>>> a = 'print'
>>> a.isidentifier()
True
>>> a = 'print is right'  #中间有空格的就不是identifier,只判断第一个单词
>>> a.isidentifier()
False
>>> a = 'printisright'
>>> a.isidentifier()
True
>>> a = 'print\tisright'
>>> a.isidentifier()
False
>>> a = 'print\nisright'
>>> a.isidentifier()
False
(14)  str.isascii() 判断字符是否纯英文字符,
>>> a = 'wo shi ella 11'
>>> a.isascii()
True
>>> a = '我是 ella 11'
>>> a.isascii()      '
False

 字符串格式化方法:

str.format()的用法:
<模板字符串>.format(<逗号分隔的参数>),
需要被format的部分用{}表示,如果想打印{},用{{}}
>>> 'hello {},hi{}'.format('world','python')
'hello world,hipython'
>>> 'hello {{{}}},hi{}'.format('world','python')
'hello {world},hipython'
>>> 'hello {2},hi{1},goodbye{0}'.format('dog','python','world')
'hello world,hipython,goodbyedog'
 
另外前面的模板字符串中大括号括起来的部分,可以定义其宽度、对齐方式、填充、精度。
>>> s = 'python'
>>> '{0}'.format(s)
'python'
>>> '{0:3}'.format(s)    #模板宽度使3,如果s宽度大于3全部显示。
'python'
>>> '{0:30}'.format(s)   #模板宽度30,如果s宽度小于30,默认左对齐,用空格补全。
'python                        '
>>> '{0:^30}'.format(s)  #^表示居中对齐,<表示左对齐,>表示右对齐
'            python            '
>>> '{0:>30}'.format(s)
'                        python'
>>> '{0:<30}'.format(s)
'python                        '
>>> '{0:+^30}'.format(s)  #‘+’的位置标明不足的位置用‘+’补齐,而不是默认的空格补齐
'++++++++++++python++++++++++++'
 
如果format的是数字,还可以format其精度,数据类型和每千位加逗号。
>>>a = 123456789.5678
>>>'{0:+^20,.2f}'.format(a)
'+++123,456,789.57+++'
注释:0后面的冒号,按顺序,
+:填充,宽度不够填充符号
^<>,居中对齐,左对齐,右对齐
20,是输出字符串宽度
,(逗号):是按千位加逗号
.2f: 是输出精度为小数点后2位float数。
如果是字符串,用.2[2前面有个点]表示精度,那么输出的就是2位字符。
比如:
>>> '{0:+^20.2}'.format('123')    #123是字符串,输出精度.2只输出12两个字符
'+++++++++12+++++++++'
>>> '{0:+^20.2f}'.format(123)    #123是数字,输出精度可以写.2f,小数点后两位数。
'+++++++123.00+++++++'
 
其他数字类型:
对于整数
>>> '{0:+^20b}'.format(123)    #b: 输出整数的二进制方式
'++++++1111011+++++++'
>>> '{0:+^20c}'.format(123)    #c:输出整数对应的unicode字符
'+++++++++{++++++++++'
>>> '{0:+^20d}'.format(123)    #d: 输出整数的十进制方式
'++++++++123+++++++++'
>>> '{0:+^20o}'.format(123)    #o: 输出整数的八进制方式
'++++++++173+++++++++'
>>> '{0:+^20x}'.format(123)    #x: 输出整数的16进制方式,小写
'+++++++++7b+++++++++'
>>> '{0:+^20X}'.format(123)    #X: 输出整数的16进制方式,大写
'+++++++++7B+++++++++'
 
对于浮点数:
>>> '{0:.2e},{0:.2E},{0:.2f},{0:.2%}'.format(3.1415)
'3.14e+00,3.14E+00,3.14,314.15%'
对于浮点数类型,输出格式包括4 种:
• e: 输出浮点数对应的小写字母 e 的指数形式;
• E: 输出浮点数对应的大写字母 E 的指数形式;
• f: 输出浮点数的标准浮点形式;
• %: 输出浮点数的百分形式。
 
format_map的用法
>>> 'hello {para1}, hi {para2}, goodbye {para3}'.format_map({'para2':'world','para3':'dog','para1':'python'})
'hello python, hi world, goodbye dog'