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

Sol*_*ull 126 python replace python-2.6

我有一个字符串.如何删除某个字符后的所有文字?(在这种情况下...)之后
的文本会...改变,所以我这就是为什么我要删除某个字符后的所有字符.

Ned*_*der 223

最多在分隔符上拆分一次,然后取出第一块:

sep = '...'
rest = text.split(sep, 1)[0]
Run Code Online (Sandbox Code Playgroud)

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

  • 如果需要从字符串末尾开始分割字符,请使用rsplit(). (4认同)

Aym*_*ieh 78

假设你的分隔符是'...',但它可以是任何字符串.

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

>>> print head
some string
Run Code Online (Sandbox Code Playgroud)

如果未找到分隔符,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 not
found, returns S and two empty strings.
Run Code Online (Sandbox Code Playgroud)

  • .partition wins - 每循环0.756 usec,而.split为1.13(评论格式化并不能让我显示确切的测试,但我正在使用@Ayman的文本和分隔符) - 所以,@ Ayman的答案为+1 ! (8认同)

the*_*cer 13

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

<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


Ale*_*lli 9

没有RE(我认为是你想要的):

def remafterellipsis(text):
  where_ellipsis = text.find('...')
  if where_ellipsis == -1:
    return text
  return text[:where_ellipsis + 3]
Run Code Online (Sandbox Code Playgroud)

或者,与RE:

import re

def remwithre(text, there=re.compile(re.escape('...')+'.*')):
  return there.sub('', text)
Run Code Online (Sandbox Code Playgroud)


小智 6

import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)
Run Code Online (Sandbox Code Playgroud)

输出:“这是一个测试”