“EOL while scanning single-quoted string”? (backslash in string)

前端 未结 5 1689
心在旅途
心在旅途 2020-12-06 08:05
import os
xp1 = \"\\Documents and Settings\\\"
xp2 = os.getenv(\"USERNAME\")
print xp1+xp2

Gives me error

 File \"1.py\", line 2 
x         


        
5条回答
  •  情话喂你
    2020-12-06 08:40

    Python, as many other languages, uses the backslash as an escape character (the double-quotes at the end of your xp1=... line are therefore considered as part of the string, not as the delimiter of the string).

    This is actually pretty basic stuff, so I strongly recommend you read the python tutorial before going any further.

    You might be interested in raw strings, which do not escape backslashes. Just add r just before the string:

    xp1 = r"\Documents and Settings\"
    

    Moreover, when manipulating file paths, you should use the os.path module, which will use "/" or "\" depending on the O.S. on which the program is run. For example:

    import os.path
    xp1 = os.path.join("data","cities","geo.txt")
    

    will produce "data/cities/geo.txt" on Linux and "data\cities\geo.txt" on Windows.

提交回复
热议问题