Pythonre.sub公司使用包含特殊字符的字符串,而不修改字符串

2024-06-26 02:04:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是为了做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}$

Tags: thetoinnewreaddatathatrandom
2条回答

转义最终反斜杠:

new_data = r'Some random text\n ' + fstring.replace('\\', r'\\')

\1通常意味着对regex匹配的组1的反向引用,但这不是您在这里想要的(事实上没有group 1,这是错误的原因),因此,您需要转义字符串,这样re不会将{}视为元字符:

fstring = r'C:\Temp\\1_file.txt'

相关问题 更多 >