Python re.sub追加字符串而不是替换它

Python re.sub追加字符串而不是替换它,python,regex,Python,Regex,我是Python新手,一直在使用正则表达式替换。我正在分析一个设置文件,其中包含以下语句: set fmri(convolve7) 3 设置文件用作模板。脚本通过模板进行解析,并使用更新的设置写入新的设置文件 我的程序的主要结构是 for line in infile: if condition = true for each in listofelements if re.search(each, line): print(re.sub(r"\d+", "0", li

我是Python新手,一直在使用正则表达式替换。我正在分析一个设置文件,其中包含以下语句:

set fmri(convolve7) 3
设置文件用作模板。脚本通过模板进行解析,并使用更新的设置写入新的设置文件

我的程序的主要结构是

for line in infile:
 if condition = true
  for each in listofelements
    if re.search(each, line):
     print(re.sub(r"\d+", "0", line), file=outfile, end='') # double output
 if re.search(somethingelse, line):
  print(re.sub(templatesubid, i, line), file=outfile, end='')# normal substitution
等等

for循环中的替换会导致双输出,而在for循环之外则不会。for循环似乎插入了具有正确替换字符串的换行符,即

set fmri(convolve7) 0
set fmri(convolve7) 3

当代码相同时,其他子状态按预期工作。可能是for循环导致了这种双重输出吗?

相关代码似乎位于底部:

    for line in infile:
        if len(subparamlist) > 0:
            for j in subparamlist:
                query = j.replace(")", "\)").replace("(", "\(")
                if re.search(query, line):
                    print(re.sub(r"\d+", "0", line), file=outfile, end='') #trouble!
        if re.search(templatesubid, line) and re.search('feat_files\(', line) or re.search('\(custom', line) : # correct the subjectID
            print(re.sub(templatesubid, i, line), file=outfile, end='')
        elif re.search(str(nptslist[2]), line): # correct the number of timepoints
            print(re.sub(str(nptslist[2]), str(nvols[0]), line), file = outfile, end='')
        else: 
            print(line, file=outfile, end='') # if nothing to do, just copy the line to the new text file.
我认为问题在于,您正在打印顶部的
if
语句(将
0
替换到行中),然后在它下面的
if/elif/else
块的一个分支中再次打印。这一结果导致部分(或全部)线路加倍


实际上,我对代码的理解还不够透彻,无法找到一个合适的修复方法,但一个可能的开始可能是将
如果
您用“更正主语”注释为
elif

您能将该代码精简为一个更简洁的示例吗?这太长了。。。你不会得到答案。。。但是re.sub确实取代了匹配项
print re.sub(“p+”、“b”、“Apple”)
因为这是python,
if条件:
就足够了,而
if条件=true
将始终为true(赋值而不是比较),我认为应该是由于缺少冒号而导致的语法错误。在任何一种情况下,您都同时命中了print语句和第二个print语句。在我的示例中,第一个if条件确实是在残废的拼音python中,您是对的,它会崩溃。更重要的是,第一个if语句捕获异常。我认为我将需要重组,并将第一个if语句提升一级。谢谢我将行更改为elif,但随后我只得到:set fmri(convolve0)0 set fmri(convolve0)0作为输出。您的建议有助于我思考-因此感谢您的快速回复!