Possible Duplicate:
why can’t I end a raw string with a \錯誤與字符串結尾反斜槓
這是爲什麼語法正確:
baseFilePath = r"C:\SVN\google code"
,而這給了錯誤
baseFilePath = r"C:\SVN\google code\"
SyntaxError: EOL while scanning string literal
Possible Duplicate:
why can’t I end a raw string with a \錯誤與字符串結尾反斜槓
這是爲什麼語法正確:
baseFilePath = r"C:\SVN\google code"
,而這給了錯誤
baseFilePath = r"C:\SVN\google code\"
SyntaxError: EOL while scanning string literal
在第二種情況下,你都逃脫報價\"
是的轉義序列210
要使用反斜槓,你應該使用一個雙反斜線\\
這應該工作:
baseFilePath = "C:\\SVN\\google code\\"
>>> print(baseFilePath)
C:\SVN\google code\
這裏,反斜槓結束"
。
如果你想在一個字符串中使用\
,最安全的方法是轉義反斜槓本身。
試試這個:
baseFilePath = "C:\\SVN\\google code\\"
我推薦它,而不是使用原始字符串。 python doc中描述了需要轉義的字符。
Fromt的docs:
When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase 'n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.
具體而言,原始字符串在 單反斜線不能結束(因爲反斜槓將難逃以下引號 字符)
據我瞭解,這是不可能在'r'字符串的末尾添加反斜槓?。它被解釋爲一個轉義序列或雙斜槓加兩次 –
使用os.path.join
,它避免了這和照顧使用操作系統相應的目錄分隔符:
>>> import os
>>> os.path.join('C:','svn','google code')
'C:/svn/google code'
不錯的功能,但我只會用它來加入變量保存路徑,在這裏我有許多手動插入的路徑頻繁變化。 –
'r「C:\\ SVN \\ google code \\」'等於'「C:\\\\ SVN \\\\ google code \\\\\\\'' – Blender
@Blender感謝您的提示,我糾正了它。 – lbonn
我使用r「語法,因爲我想避免所有情況下的雙斜線。 –