我的问题是,为了做子我需要转义特殊字符。但我不想修改我替换的字符串。 Python有办法处理这个吗?返回Python re.sub中包含特殊字符而不修改字符串的字符串
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
错误becasue在在“\ 1”“一个fstring”被看作是一个组对象。
error: invalid group reference
I *认为*您可能需要在原始字符串中转义它。你可以试试'fstring = r'C:\ Temp \\ 1_file.txt''? –
谢谢,这有效,但由于我在很多文件中阅读,我不想编写额外的代码来修改每个文件,如果我可以避免它。猜猜这不是什么大问题。 – sparrow
呃,这个网站有时候很烦人。为什么要投票? – sparrow