[英]How to replace backslash with forward slash - Python
I wrote this simple little program: 我写了这个简单的小程序:
def main ( ):
with open("test.txt", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line.replace("\", "/"))
print ("done")
main () 主要()
I know that "\\" is an escape literal in Python but all I need is to scan through the text file and replace every single backlash with a forward slash "/". 我知道“ \\”是Python中的转义文字,但是我需要浏览整个文本文件,并用正斜杠“ /”替换每个反斜杠。
Anyone knows what to do? 有人知道该怎么办吗?
You have to remember that strings in python are interpreted. 您必须记住python中的字符串被解释了。 Only raw strings do not follow this rule.
仅原始字符串不遵循此规则。 Here I mean that if for example you have a
"\\n"
included in your string, it would be interpreted as a new line. 在这里,我的意思是,例如,如果您的字符串中包含
"\\n"
,它将被解释为新行。 Fortunately strings read from file are already raw. 幸运的是,从文件读取的字符串已经是原始的。
All you have to do is simply use the regular expression: 您只需要使用正则表达式即可:
s.replace('\\','/')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.