Python:使用re.substitute作为模板时保持行格式(breaklines)

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

我正在从多个文件中获取有关点的信息,并根据模板为每个点创建新文件。有问题的文件看起来像这样

...
Point number:"Number" {
 info
 info
}
...
Point number:"Number" {
 info
 info 
 info
 info
}
...
etc

带有信息的行数可以变化。

我正在使用re.findall()来搜索这样的点

point_info = re.findall(r"(?ms)^P.*?{$.*?^};$", file.read())

但是当我试着把它放在我的模板中时,我得到了

['Point number:"Number" { \n  info \n  info \n  info \n  info \n }']

我使用.substitute将信息插入模板。模板看起来像这样

Template
... 
...
...
$point_info 
...
...

输入代码时

d = {'point_info ': point_info }
result = src.substitute(d)
output_file.write(result) #opened beforehand

如何让我的输出看起来与主文件中的完全一样,请记住线条数量可能有所不同? (模板有很多其他$变量,这里没有提到)

python templates string-formatting
1个回答
0
投票

我设法通过使用.join()函数来解决这个问题。 point_info =''.join(point_info)给了我预期的结果

© www.soinside.com 2019 - 2024. All rights reserved.