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

2024-04-19 03:01:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根绳子。如何删除某个字符后的所有文本?(在这种情况下...
后面的文本将发生变化,因此我希望删除某个字符之后的所有字符。


Tags: 文本情况字符绳子
3条回答

最多一次在你的分隔器上分开,拿第一块:

sep = '...'
rest = text.split(sep, 1)[0]

你没说如果分隔符不存在会发生什么。在这种情况下,这个和Alex的解决方案都将返回整个字符串。

如果要删除字符串中最后一次出现分隔符之后的所有内容,我发现这很有效:

<separator>.join(string_to_split.split(<separator>)[:-1])

例如,如果string_to_split是一个类似于root/location/child/too_far.exe的路径,并且您只需要文件夹路径,那么可以按"/".join(string_to_split.split("/")[:-1])分割,您将得到 root/location/child

假设分隔符是“…”,但它可以是任何字符串。

text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')

>>> print head
some string

如果找不到分隔符,head将包含所有原始字符串。

分区函数是在Python2.5中添加的。

partition(...) 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 not
found, returns S and two empty strings.

相关问题 更多 >