python - 在第 n 次出现后删除字符串的其余部分

标签 python regex string python-2.7 python-2.x

我有以下字符串:

a = "this.is.a.string"

我希望删除第三个“.”之后的所有内容符号,以便它返回

trim(a)
>>> "this.is.a"

而没有第三个'.'的字符串应该返回自己。

这个答案 ( How to remove all characters after a specific character in python? ) 是我能找到的最接近的解决方案,但是我认为 split 这次对我没有帮助。

最佳答案

.split()通过然后.join() :

>>> ".".join(a.split(".")[:3])
'this.is.a'

您还可以指定 maxsplit 参数,因为您只需要 3 个“切片”:

If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

>>> ".".join(a.split(".", 3)[:-1])
'this.is.a'

关于python - 在第 n 次出现后删除字符串的其余部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35109927/

相关文章:

javascript - 如何在 JavaScript 中用 "underscore"( "_ ") 替换字符串的 80%?

java - 删除java中字符之前和之后的字符

python - 正则表达式与我认为应该匹配的不匹配

python - 相对 shebang : How to write an executable script running portable interpreter which comes with it

python - 如何根据python中的数组值对列表进行排序?

python - 如何在虚拟环境中使用 pip nodjs 安装 jupyterlab-plotly labextension?

python - 如何排除包含常量字符串的正则表达式匹配

Java 正则表达式困惑

C++ DLL 只读取 safearray 中包含的字符串的第一个字符

python - MySQL from_unixtime() 和 Python time.ctime() 不一致