如何在python中的特定字符之后删除所有字符? 我有一个字符串。如何在特定字符之后删除所有文本? (在这种情况下 ...) 随后的文字...更改,所以我就是为什么要在某个字符之后删除所有字符的原因。

问题描述 投票:0回答:10

最多一次放在分离器上,然后拿第一件:

...

如果不存在分离器,您没有说应该发生什么。 在这种情况下,这和alex的解决方案都会返回整个字符串。

填充分离器是“ ...”,但可以是任何字符串。

sep = '...' stripped = text.split(sep, 1)[0]
python replace
10个回答
408
投票
如果找不到分离器,

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

将包含所有原始字符串。
python 2.5中添加了
分区函数。

head

->

141
投票

搜索分隔符
Sep

S

中,然后返回其前面的零件,
分离器本身和之后的部分。如果分离器不是
发现,返回
S

和两个空字符串。

如果您想在最后一次出现分隔符后删除所有内容,我发现这很好:

(head, sep, tail)
,例如,如果

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

是像string_to_split这样的路径,而您只需要文件夹路径,则可以通过root/location/child/too_far.exe拆分,您将得到 "/".join(string_to_split.split("/")[:-1])


34
投票
没有正则表达式(我认为这是您想要的):

root/location/child

或带有正则表达式:

def remafterellipsis(text): where_ellipsis = text.find('...') if where_ellipsis == -1: return text return text[:where_ellipsis + 3]


import re

def remwithre(text, there=re.compile(re.escape('...')+'.*')):
  return there.sub('', text)
输出:“这是一个测试”

方法查找将返回字符串中的字符位置。然后,如果您想从角色中删除所有内容,请执行此操作:

11
投票
import re test = "This is a test...we should not be able to see this" res = re.sub(r'\.\.\..*',"",test) print(res)

如果您想保持角色,请在字符位置上加1个。

从文件:

mystring = "123⋯567"
mystring[ 0 : mystring.index("⋯")]

>> '123'

6
投票
替换替代者:

import re sep = '...' with open("requirements.txt") as file_in: lines = [] for line in file_in: res = line.split(sep, 1)[0] print(res)

原始答案:

4
投票


这在Python 3.7为我工作 在我的情况下,我需要在DOT中删除字符串可变费用


3
投票
split_string = fees.split(“。”,1)

substring = split_string [0]
PRINT(substring)

3
投票

在字符串中出现字符之后,删除所有字符的另一种方法(假设您想在最终'/':)之后删除所有字符。

text, *_ = text.partition('...')
    

使用path = 'I/only/want/the/containing/directory/not/the/file.txt' while path[-1] != '/': path = path[:-1]


0
投票
模块的简便方法
re

如果您需要区分第一和最后一次,则可能会派上用场。

import re, clr text = 'some string... this part will be removed.' text= re.search(r'(\A.*)\.\.\..+',url,re.DOTALL|re.IGNORECASE).group(1) // text = some string

,但是,对于解析URL,最好使用

str.find


0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.