这篇文章将为大家详细讲解有关python怎样去除字符串头尾的多余符号,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
在读文件时常常得到一些\n和引号之类的符号,可以使用字符串的成员函数strip()来去除。
1.去除首尾不需要的字符
a= '"This is test string"' # strip()会默认去除'\n','\r','\t',' ',制表回车换行和空格等字符
a.strip('"')
>>> 'This is test string'
b = ' This is another string ' #首尾两个空格
b.strip(' ')
>>>'This is another string'
b.strip()
>>>'This is another string' # 默认去除
c = '*This is an-another string/' # 首尾两个字符
c.strip('*/') #这里strip将解析每一个字符,检查首尾是否存在,存在就去除返回
>>>'This is an-another string'
d = '//This is the last string**'
d.strip('*/')
>>> d = 'This is the last string' # 持续去除首尾的指定字符符号
e = 'einstance'
e.strip('e') # 去除首尾特定字符
>>> 'instanc'
2.去除末尾特定字符
专治末尾多余字符rstrip()
a = ' example '
a.rstrip() #同样默认去除末尾的空格\n,\t,\r
>>>' example'
b = 'this is mya'
b.rstrip('a') #去除末尾特定字符
>>>'this is my'
3.去除开头特定字符
专治开头多余字符lstrip()
a = ' example '
a.lstrip() #默认去除开头的空格\n,\t,\r
>>>'example '
b = 'athis is mya'
b.lstrip('a') #去除末尾特定字符
>>>'this is mya'
4.去除字符串中的特定字符
一种常见的方法是转换为list,再使用remove方法,随后再转换为string,这里再额外说明两种方法。使用replace()和re.sub()
# 使用字符串replace()方法,将目标字符替换为空
a = 'this is the test'
a.replace('t','')
>>>'his is he es'
#第二种方法使用正则表达式方法
import re
re.sub('s','', a)
>>>'thi i the tet'
5.巧用eval()函数
eval函数的作用是将传入的字符串作为表达式来进行计算,可以有效去除(双)引号,空格等字符。
a = ' "This is a good example" '
eval(a)
>>>`This is a good example`
b = ' "This is a good example" '
eval(b)
>>>'This is a good example'
重要提示:字符串外面的引号和字符串内的引号不能同时使用单引号或双引号,外面用了单引号里面只能用双引号,否则会引起异常。
关于“python怎样去除字符串头尾的多余符号”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。