我的問題是,爲了做子我需要轉義特殊字符。但我不想修改我替換的字符串。 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