2017-02-26 158 views
0

我写了这个简单的小程序:如何替换斜杠反斜杠 - 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") 

的main()

我知道,“\”是在Python字面逃跑,但我需要的是扫描文本文件并用正斜杠“/”替换每一个间隙。

任何人都知道该怎么办?

+0

也许用“\\”呢? –

+1

[在Python中用正斜杠替换反斜杠]的可能重复(http://stackoverflow.com/questions/4119166/replace-backslashes-with-forward-slashes-in-python) – McGrady

回答

1

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

所有你需要做的就是简单地使用正则表达式:

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

谢谢!这似乎解决了我遇到的问题。 – teleton11

+0

您知道如何用'somestring'替换'\'',如... 'hello \'以替换'.replace('\'','\\“')... 这似乎不是工作。 – zochhuana

+0

使用级联替换: ''hello \'替换'.replace('\\','').replace(''','')' – adgon92