如何删除python中特定字符之后的所有字符?

我有一个字符串。如何删除某个字符后的所有文本?(在这种情况下...)之后

的文本将...更改,所以这就是为什么我要删除某个字符之后的所有字符的原因。


互换的青春
浏览 9019回答 3
3回答

红糖糍粑

假设分隔符为“ ...”,但它可以是任何字符串。text = 'some string... this part will be removed.'head, sep, tail = text.partition('...')>>> print headsome string如果找不到分隔符,head将包含所有原始字符串。分区功能是在Python 2.5中添加的。分区(...)S.partition(sep)->(head,sep,tail)Searches for the separator sep in S, and returns the part before it,the separator itself, and the part after it.  If the separator is notfound, returns S and two empty strings.

慕村225694

如果要删除字符串中最后一次出现分隔符之后的所有内容,我会发现这很有效:<separator>.join(string_to_split.split(<separator>)[:-1])例如,如果&nbsp; string_to_split是像一个路径root/location/child/too_far.exe,你只需要在文件夹路径,您可以通过拆分"/".join(string_to_split.split("/")[:-1]),你就会得到 root/location/child
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python