我有以下字符串:
a = "this.is.a.string"
我希望删除第三个“.”之后的所有内容符号,以便它返回
trim(a)
>>> "this.is.a"
而没有第三个“.”的字符串应该返回自身。
这个答案(如何删除python中特定字符之后的所有字符? https://stackoverflow.com/questions/904746/how-to-remove-all-characters-after-a-specific-character-in-python)是我能找到的最接近的解决方案,但我不认为split
这次会帮助我的。
.split() https://docs.python.org/2/library/stdtypes.html#str.split by the dot
进而.join() https://docs.python.org/2/library/stdtypes.html#str.join:
>>> ".".join(a.split(".")[:3])
'this.is.a'
您还可以指定maxsplit
争论,因为你只需要 3 个“切片”:
If maxsplit
最多给定maxsplit
分割完成(因此,列表最多有maxsplit+1
元素)。
>>> ".".join(a.split(".", 3)[:-1])
'this.is.a'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)