Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用正斜杠替换反斜杠-Python_Python_File_Escaping_Backslash - Fatal编程技术网

如何用正斜杠替换反斜杠-Python

如何用正斜杠替换反斜杠-Python,python,file,escaping,backslash,Python,File,Escaping,Backslash,我写了一个简单的小程序: 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") 主要 我知道\在Python中是转义文字,但我只需要扫描文本文件并用正斜杠/替换每个反冲 有人知道该怎

我写了一个简单的小程序:

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")
主要

我知道\在Python中是转义文字,但我只需要扫描文本文件并用正斜杠/替换每个反冲


有人知道该怎么做吗?

您必须记住python中的字符串是解释的。只有原始字符串不遵循此规则。这里我的意思是,例如,如果字符串中包含一个\n,它将被解释为新行。 幸运的是,从文件中读取的字符串已经是原始字符串

只需使用正则表达式即可:

s.replace('\\','/')

可能改用\\?可能是重复的谢谢!这似乎解决了我遇到的问题。你知道如何用“somestring”替换“\”,如…'您好\要替换“”。替换“\”,“\ \”。。。这似乎不起作用。请使用替换的级联:“hello\to replace”。替换“\\”,.replace“”,