神剑山庄资源网 Design By www.hcban.com
在读文件时常常得到一些\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 如何去除字符串头尾的多余符号,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com
暂无python 如何去除字符串头尾的多余符号的评论...
更新日志
2024年09月30日
2024年09月30日
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】