繁体   English   中英

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

[英]How to remove all characters after a specific character in python?

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

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

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

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

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

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

>>> print head
some string

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

分区函数是在 Python 2.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.

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

<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

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

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

或者,使用 RE:

import re

def remwithre(text, there=re.compile(re.escape('...')+'.*')):
  return there.sub('', text)
import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)

输出:“这是一个测试”

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

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

>> '123'

如果要保留字符,请在字符位置加 1。

从文件:

import re
sep = '...'

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

使用 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

这是在 python 3.7 中对我工作在我的情况下,我需要在我的字符串变量费用中删除点之后

费用 = 45.05
split_string = fee.split(".", 1)

子字符串 = split_string[0]

打印(子字符串)

另一种在字符串中最后一次出现字符后删除所有字符的方法(假设您要删除最后一个“/”后的所有字符)。

path = 'I/only/want/the/containing/directory/not/the/file.txt'

while path[-1] != '/':
    path = path[:-1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM