我有以下字符串:
a = "this.is.a.string"
我希望删除第三个“.”之后的所有内容符号,以便它返回
trim(a)
>>> "this.is.a"
而没有第三个'.'的字符串应该返回自己。
这个答案 ( How to remove all characters after a specific character in python? ) 是我能找到的最接近的解决方案,但是我认为 split
这次对我没有帮助。
最佳答案
>>> ".".join(a.split(".")[:3])
'this.is.a'
您还可以指定 maxsplit
参数,因为您只需要 3 个“切片”:
If
maxsplit
is given, at mostmaxsplit
splits are done (thus, the list will have at mostmaxsplit+1
elements).
>>> ".".join(a.split(".", 3)[:-1])
'this.is.a'
关于python - 在第 n 次出现后删除字符串的其余部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35109927/