1

Possible Duplicate:
why can’t I end a raw string with a \

Why is this syntax correct:

baseFilePath = r"C:\SVN\google code"

while this gives the error

baseFilePath = r"C:\SVN\google code\"

SyntaxError: EOL while scanning string literal

Community
  • 1
  • 1
Matthias Pospiech
  • 3,130
  • 18
  • 55
  • 76

4 Answers4

2

Fromt the 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.

Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character)

sberry
  • 128,281
  • 18
  • 138
  • 165
  • As far as I understand this there is no possibility to add a backslash at the end of a 'r' string ?. It is either interpreted as a escape sequence or with double slashes added twice. – Matthias Pospiech Jan 06 '13 at 09:50
1

In the second case, you are escaping the quote \" is the escape sequence for a "

To use the backslash, you should use a double backslash \\

This should work :

baseFilePath = "C:\\SVN\\google code\\"

>>> print(baseFilePath)
    C:\SVN\google code\
asheeshr
  • 4,088
  • 6
  • 31
  • 50
1

Use os.path.join, it avoids this and takes care of using the OS-appropriate directory separators:

>>> import os
>>> os.path.join('C:','svn','google code')
'C:/svn/google code'
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • nice function, but I would only use it to join variables holding paths. Here I have many manually inserted paths that change frequently. – Matthias Pospiech Jan 06 '13 at 09:24
0

Here, the backslash escapes the ending ".
If you want to use \ in a string, the most safe way is to escape the backslash itself.

Try this:

baseFilePath = "C:\\SVN\\google code\\"

I'd recommend it instead of using a raw string. The characters which need an escape are described in the python doc.

lbonn
  • 2,499
  • 22
  • 32