如何去掉字符串的左侧部分?

173

我有一些简单的Python代码,用于在文件中搜索一个字符串,例如path=c:\path,其中c:\path部分可能会有所变化。当前的代码是:

def find_path(i_file):
    lines = open(i_file).readlines()
    for line in lines:
        if line.startswith("Path="):
            return # what to do here in order to get line content after "Path=" ?

如何简单获取 Path= 后面的文本?


请注意,您正在返回文件中以“Path =”开头的第一行出现。其他回答也是如此。但是,如果文件类似于DOS批处理文件,则根据“批处理”或命令文件是否填充有条件,您可能实际上想要从该文件获取最后一行出现。 - DevPlayer
21个回答

4
import re

p = re.compile(r'path=(.*)', re.IGNORECASE)

path = r"path=c:\path"

re.match(p, path).group(1)

输出:

'c:\\path'

4
Python 3.9 中新增了 removeprefix()removesuffix() 字符串方法,由于 lstriprstrip 解释传递给它们的参数的问题。阅读 PEP 616 了解更多详情。
# in python 3.9
>>> s = 'python_390a6'

# apply removeprefix()
>>> s.removeprefix('python_')
'390a6'

# apply removesuffix()
>>> s = 'python.exe'
>>> s.removesuffix('.exe')
'python'

# in python 3.8 or before
>>> s = 'python_390a6'
>>> s.lstrip('python_')
'390a6'

>>> s = 'python.exe'
>>> s.rstrip('.exe')
'python'

removesuffix示例列表:

plurals = ['cars', 'phones', 'stars', 'books']
suffix = 's'

for plural in plurals:
    print(plural.removesuffix(suffix))

输出:

car
phone
star
book

removeprefix函数在列表中的示例:

places = ['New York', 'New Zealand', 'New Delhi', 'New Now']

shortened = [place.removeprefix('New ') for place in places]
print(shortened)

输出:

['York', 'Zealand', 'Delhi', 'Now']

3
line[5:]

给你第五个字符之后的所有字符。


2

line[5:] 将给出您想要的子字符串。搜索介绍并查找“切片表示法”。


2
为什么不使用转义的正则表达式? ^可以匹配每行的开头,而re.MULTILINE可以匹配每一行。re.escape可以确保精确匹配。
>>> print(re.sub('^' + re.escape('path='), repl='', string='path=c:\path\nd:\path2', flags=re.MULTILINE))
c:\path
d:\path2

1
如果你了解列表推导式:
lines = [line[5:] for line in file.readlines() if line[:5] == "Path="]

有一个编辑建议使用 line.startswith(...) 可以快10倍。但我的测试并没有证实这一点。如果提供支持该断言的证据,我很乐意进行更改。 - Matthew Schinckel

0
尝试以下代码。
if line.startswith("Path="): return line[5:]

2
你的答案和被接受的答案有什么区别?我看到它在另一个答案的前半部分。 - eyllanesc

-1

我猜这正是你正在寻找的

    def findPath(i_file) :
        lines = open( i_file ).readlines()
        for line in lines :
            if line.startswith( "Path=" ):
                output_line=line[(line.find("Path=")+len("Path=")):]
                return output_line

-2

不需要编写函数,这将根据列表进行拆分,在本例中为'Mr.|Dr.|Mrs.',选择拆分后的[1]之后的所有内容,然后再次拆分并获取任何元素。在下面的情况下,返回'Morris'。

re.split('Mr.|Dr.|Mrs.', 'Mr. Morgan Morris')[1].split()[1]

-2
可以尝试下面的方法。
def remove_suffix(string1, suffix):
    length = len(suffix)

    if string1[0:length] == suffix:
        return string1[length:]
    else:
        return string1

suffix = "hello"
string1 = "hello world"

final_string = remove_suffix(string1, suffix)
print (final_string)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接