我有一些简单的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=之后的文本的简单方法是什么
发布于 2020-04-26 05:01:57
从Python 3.9开始,您可以使用removeprefix
'Path=helloworld'.removeprefix('Path=')
# 'helloworld'发布于 2009-03-01 15:26:57
如果字符串是固定的,您可以简单地使用:
if line.startswith("Path="):
return line[5:]它提供了从字符串中位置5开始的所有内容(字符串也是一个序列,因此这些序列操作符也可以在这里使用)。
或者,您可以在第一个=处拆分该行
if "=" in line:
param, value = line.split("=",1)那么param就是"Path“,value就是第一个=之后的剩余部分。
发布于 2009-03-01 18:03:24
从字符串中删除前缀
# ...
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其他选项
https://stackoverflow.com/questions/599953
复制相似问题