品易云推流 关闭
文章详情页
文章 > Python基础教程 > python删除str中特定字符的方法

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

python删除

头像

小妮浅浅

2021-08-05 09:41:4213250浏览 · 0收藏 · 0评论

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

以上就是python删除str中特定字符的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图