Quoting backslashes in Python string literals

前端 未结 4 677
独厮守ぢ
独厮守ぢ 2020-11-22 16:21

I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are eit

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 17:17

    What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.

    infile = open('c:/folder/subfolder/file.txt')
    

    The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system or the subprocess module).

提交回复
热议问题