Python raw string generation error with trailing slash

I am trying to set the path to a string variable in python using raw string notation, and I get an error with a trailing slash:

datapath = r'C:\path\to\my\data\' 

gives me the error "EOL while scanning a string literal"

I thought that writing to a string string should have done everything in a string literal. Can someone explain this to me?

thanks

+5
source share
2 answers

There is an exception for the final quote of a string, because:

 C:\path\to\my\data\' 

sees ' literally, since the previous backslash is not considered an escape char, so parsing the strings continues.

Since this is frustrating, you need to do r'C:\path\to\my\data\\'

+3
source

The documentation defines a string literal like this:

 stringliteral ::= [stringprefix](shortstring | longstring) 

You are using the string value r .

Then we have these definitions for the characters in the lines:

 shortstringchar ::= <any source character except "\" or newline or the quote> longstringchar ::= <any source character except "\"> 

where you will notice that the backslash is not one of the characters allowed in a short line or a long line.

+2
source

Source: https://habr.com/ru/post/1262380/


All Articles