Python 去除字符串中指定字符串
1、背景
最近的项目中,再次踩到Python字符串处理的坑,决定把此次解决方案记录一下,以勿踩坑。
2、遇到坑
原本字符串:大坪英利国际8号楼88-88号重庆汉乔科技有限公司大坪英利国际8号楼
去除最左边的字符串:大坪英利国际8号楼
预期结果:88-88号重庆汉乔科技有限公司大坪英利国际8号楼
自然而然,第一个想到的就是lstrip()函数。
Python中lstrip()方法用于截掉字符串左边的空格或指定字符。
但实际上结果:
lstrip:-88号重庆汉乔科技有限公司大坪英利国际8号楼
3、找到lstrip()坑的真相
函数原型:
deflstrip(self,chars=None):#realsignatureunknown;restoredfrom__doc__ """ S.lstrip([chars])->str ReturnacopyofthestringSwithleadingwhitespaceremoved. IfcharsisgivenandnotNone,removecharactersincharsinstead. """ return""
看来lstrip方法是比对字符并去除,而不是简单的去除最左边字符串。
那好,再验证一下:
"重庆重庆师范大学".lstrip("重庆")
结果:
师范大学
那我想简单的去除字符串中的首个指定字符串,最好不用lstrip()了。
于是又想到了split方法和replace方法……
4、解决方案
4.1、方法1split
函数原型:
defsplit(self,instring,maxsplit=_MAX_INT,includeSeparators=False): """ Generatormethodtosplitastringusingthegivenexpressionasaseparator. MaybecalledwithoptionalC{maxsplit}argument,tolimitthenumberofsplits; andtheoptionalC{includeSeparators}argument(default=C{False}),iftheseparating matchingtextshouldbeincludedinthesplitresults. Example:: punc=oneOf(list(".,;:/-!?")) print(list(punc.split("This,this?,thissentence,isbadlypunctuated!"))) prints:: ['This','this','','thissentence','isbadlypunctuated',''] """ splits=0 last=0 fort,s,einself.scanString(instring,maxMatches=maxsplit): yieldinstring[last:s] ifincludeSeparators: yieldt[0] last=e yieldinstring[last:]
4.2、方法2replace
函数原型:
defreplace(self,old,new,count=None): """ Foreachelementin`self`,returnacopyofthestringwithall occurrencesofsubstring`old`replacedby`new`. Seealso -------- char.replace """ returnasarray(replace(self,old,new,count))
5、案例
5.1、源代码
#-*-coding:utf-8-*- """ Author:ZhenYuSha CreateTime:2020-2-26 Info:去除字符串中首个指定字符串 """ defrun(source,key): tmp_ls=source.lstrip(key) tmp_re=source.replace(key,"",1) tmp_sp=source.split(key,1)[1] returntmp_ls,tmp_re,tmp_sp if__name__=='__main__': tmp_1,tmp_2,tmp_3=run("大坪英利国际8号楼88-88号重庆汉乔科技有限公司大坪英利国际8号楼","大坪英利国际8号楼") print("test_1lstrip:",tmp_1) print("test_1replace:",tmp_2) print("test_1split:",tmp_3) tmp_1,tmp_2,tmp_3=run("重庆重庆师范大学","重庆") print("test_2lstrip:",tmp_1) print("test_2replace:",tmp_2) print("test_2split:",tmp_3)
5.2、效果
6、延伸
split和replace可以解决字符串首个指定字符串去除问题,但去除字符串这个问题不仅仅是去除就完了,还要去判断是否符合我们的要求。
6.1、看字符串开头是否是指定字符串
如果需要以指定字符串开头,要用startswith函数来判断。
6.2、看字符串中是否存在指定字符串
如果不存在指定字符串,直接用split和replace会直接崩溃的,那就需要find函数来查看了。
到此这篇关于Python去除字符串中指定字符串的文章就介绍到这了,更多相关Python去除字符串内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。