码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-05-17 13:25:33      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:python   字符串   strip   作用   替换   amp   长度   ref   translate   

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

 

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

标签:python   字符串   strip   作用   替换   amp   长度   ref   translate   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!