如何删除字符串的左侧部分?

我有一些简单的 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=之后得到文本的简单方法是什么?

295549 次浏览

我能想到的最简单的方法就是切片:

def find_path(i_file):
lines = open(i_file).readlines()
for line in lines:
if line.startswith("Path=") :
return line[5:]

关于片符号的一个快速注释,它使用了两个索引而不是通常的索引。第一个索引表示您希望包含在 切片中的序列的第一个元素,最后一个索引是您希望包含在切片中的最后一个元素之后的索引。
例如:

sequence_obj[first_index:last_index]

该切片由 first_indexlast_index之间的所有元素组成,包括 first_index而不是 last_index。如果省略第一个索引,则默认为序列的开始。如果省略最后一个索引,则它包含序列中最后一个元素之前的所有元素。负指数也是允许的。使用谷歌了解更多关于这个主题的信息。

line[5:]

在前五个之后给你字符。

line[5:]将提供所需的子字符串。搜索 介绍并查找“切片表示法”

如果字符串是固定的,你可以简单地使用:

if line.startswith("Path="):
return line[5:]

从字符串的第5个位置开始(字符串也是一个序列,所以这些序列运算符在这里也起作用)。

或者你可以在第一个 =分割线:

if "=" in line:
param, value = line.split("=",1)

然后 param 是“ Path”,value 是第一个 = 后面的其余部分。

对于切片(有条件的或无条件的) ,通常我更喜欢同事最近提出的建议: 使用空字符串替换。更容易阅读代码,代码(有时)更少,指定错误字符数的风险也更小。好的,我不使用 Python,但是在其他语言中我更喜欢这种方法:

rightmost = full_path.replace('Path=', '', 1)

或者-跟进这篇文章的第一条评论-如果这只能在 如果开始排队的话Path中完成:

rightmost = re.compile('^Path=').sub('', full_path)

上面提到的主要区别在于没有“魔术数字”(5) ,也不需要同时指定“ 5还有和字符串“ Path=”。换句话说,从代码维护的角度来看,我更喜欢这种方法。

import re


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


path = "path=c:\path"


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

产出:

'c:\\path'

从字符串中删除前缀

# ...
if line.startswith(prefix):
return line[len(prefix):]

通过 str.partition()在分离器的第一次出现时分离

def findvar(filename, varname="Path", sep="=") :
for line in open(filename):
if line.startswith(varname + sep):
head, sep_, tail = line.partition(sep) # instead of `str.split()`
assert head == varname
assert sep_ == sep
return tail

ConfigParser解析类 INI 文件

from ConfigParser import SafeConfigParser
config = SafeConfigParser()
config.read(filename) # requires section headers to be present


path = config.get(section, 'path', raw=1) # case-insensitive, no interpolation

其他选择

如果你知道列表理解法:

lines = [line[5:] for line in file.readlines() if line[:5] == "Path="]

比起索引 [-1],我更喜欢 pop:

value = line.split("Path=", 1).pop()

value = line.split("Path=", 1)[1]
param, value = line.split("Path=", 1)

Python 3.9 +

text.removeprefix(prefix)

任何 Python 版本:

def remove_prefix(text, prefix):
return text[len(prefix):] if text.startswith(prefix) else text

为什么不呢

if line.startswith(prefix):
return line.replace(prefix, '', 1)

不如..。

line = r'path=c:\path'
line.partition('path=')

产出:

('', 'path=', 'c:\\path')

这个三联体就是 头部,分离器,尾部

我想这正是你想要的

    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

流行版本不太对,我想你想要:

>>> print('foofoobar'.split('foo', 1).pop())
foobar

这里还有一个没有提到的简单笑话:

value = line.split("Path=", 1)[-1]

这也适用于各种边缘情况:

>>> print("prefixfoobar".split("foo", 1)[-1])
"bar"


>>> print("foofoobar".split("foo", 1)[-1])
"foobar"


>>> print("foobar".split("foo", 1)[-1])
"bar"


>>> print("bar".split("foo", 1)[-1])
"bar"


>>> print("".split("foo", 1)[-1])
""

不需要编写函数,它将根据列表进行分割,在这种情况下是‘ Mr. | Dr. | Mr.’,用[1]分割后选择所有内容,然后再次分割并获取任何元素。在下面的例子中,返回“ Morris”。

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

为什么不在转义中使用正则表达式? ^匹配行的初始部分,re.MULTILINE匹配每一行。re.escape确保匹配是精确的。

>>> print(re.sub('^' + re.escape('path='), repl='', string='path=c:\path\nd:\path2', flags=re.MULTILINE))
c:\path
d:\path2

这和其他答案在技巧上非常相似,但是没有重复的字符串运算,能够判断前缀是否存在,而且仍然相当可读:

parts = the_string.split(prefix_to_remove, 1):
if len(parts) == 2:
#  do things with parts[1]
pass

尝试遵循代码

if line.startswith("Path="): return line[5:]

Python 3.9开始,你可以使用 removeprefix:

'Path=helloworld'.removeprefix('Path=')
# 'helloworld'

removeprefix()removesuffix()字符串方法由于与 lstriprstrip解释传递给它们的参数有关的问题而添加到 Python 3.9中。阅读 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']

可以尝试下面的方法。

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)