Python:字符串函数

时间:2025-04-17 07:44:03

返回某字符串所有匹配项均被替换之后得到的字符串,原字符串不改变

>>> word = 'this is a test'
>>> ('is', 'eez')
'theez eez a test'
>>> word
'this is a test'

maketrans函数:功能同上,string中的转换表,共有256个项目,函数接受2个等长的字符串,第一个字符串中的每个字符都用第二个字符串中相应位置的字符来进行替换

maketrans类似于一种规则,经常与translate结合,以完成一些普通函数无法完成的字符串替换

>>> from string import maketrans
>>> table = maketrans('cs', 'kz')
>>> len(table)
256
>>> table[97:123]
'abkdefghijklmnopqrztuvwxyz'
>>> maketrans('','')[97:123]
'abcdefghijklmnopqrstuvwxyz'

translate函数:功能同上,但是只能处理单个字符,有2个参数,第一个是替换,第二个是删除

例:table承继maketrans中的table

>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
>>> 'this is an incredible test'.translate(table, ' ')
'thizizaninkredibletezt'