删除或替换字符串中特定字符

1 replace( )

replace()函数只有三个参数,第三个参数是最大替代次数

特别注意replace()函数作用完后,并没有改变原字符串

参考:https://www.runoob.com/python/att-string-replace.html

2 strip( )

strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列

参考:https://www.runoob.com/python/att-string-strip.html

3 lstrip( )

lstrip() 方法用于截掉字符串左边的空格或指定字符

参考:https://www.runoob.com/python/att-string-lstrip.html

4 rstrip( )

rstrip() 删除 string 字符串末尾的指定字符(默认为空格)

参考:https://www.runoob.com/python/att-string-rstrip.html

5 maketrans( )   translate( )

当有两个参数替换时要保证替换前后长度相等,

intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)  # 制作翻译表

str = "this is string example....wow!!!"
print(str.translate(trantab))
# th3s 3s str3ng 2x1mpl2....w4w!!!

当有三个参数时,可以实现删除功能,如下:

i = 'hello world i am li'
print(i.translate(str.maketrans('','','l')))
# heo word i am i

参考:https://www.runoob.com/python3/python3-string-translate.html

原文地址:https://www.cnblogs.com/xxswkl/p/10880695.html