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 th
e 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
python 正则表达式 空格
>>>'example '
b = 'athis is mya'
b.lstrip('a') #去除末尾特定字符
>>>'this is mya'
4.去除字符串中的特定字符
⼀种常见的⽅法是转换为list,再使⽤remove⽅法,随后再转换为string,这⾥再额外说明两种⽅法。使⽤replace()和re.sub() # 使⽤字符串replace()⽅法,将⽬标字符替换为空
a = 'this is the test'
>>>'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 如何去除字符串头尾的多余符号,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!
如果你觉得本⽂对你有帮助,欢迎转载,烦请注明出处,谢谢!