简体   繁体   中英

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 "/".

Anyone knows what to do?

You have to remember that strings in python are interpreted. 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. Fortunately strings read from file are already raw.

All you have to do is simply use the regular expression:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM