python删除str中特定字符的方法

1,384次阅读
没有评论

python删除str中特定字符的方法

1、删除字符串首尾的多余字符串strip()

# 删除字符串中多余字符
def string_remove():
   str1 = ' abc     \n'
   print str1.strip()   # abc
 
   str2 = '----abcdf++++'
   print str2.strip('-+')  # abcdf

2、replace函数,删除字符串中某一个所有的字符串

ss = 'old old string'
ret = ss.replace('old', 'new', 1)
print(ret)

3、sub函数,同时删除多个字符串,使用正则表达式

str2 = '\nabc\nwrt22\t666\t'  # 删除字符串中的所有\n,\t
import re
print(re.sub('[\n\t]','',str2))   # abcwrt22666
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-07-23发表,共计474字。
新手QQ群:570568346,欢迎进群讨论 Python51学习