我的问题是为了做sub我需要逃离一个特殊的角色。但我不想修改我要替换的字符串。Python有办法处理这个问题吗?在
fstring = r'C:\Temp\1_file.txt' #this is the new data that I want to substitute in
old_data = r'Some random text\n .*' #I'm looking for this in the file that I'll read
new_data = r'Some random text\n '+fstring #I want to change it to this
f = open(myfile,'r') #open the file
filedata = f.read() #read the file
f.close()
newfiledata = re.sub(old_data,new_data,filedata) #substitute the new data
返回错误,因为“fstring”中的“\1”被视为组对象。在
^{pr2}$
转义最终反斜杠:
\1
通常意味着对regex匹配的组1的反向引用,但这不是您在这里想要的(事实上没有group 1,这是错误的原因),因此,您需要转义字符串,这样re
不会将{相关问题 更多 >
编程相关推荐