Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I end a raw string with a backslash? [duplicate]

I am confused here, even though raw strings convert every \ to \\ but when this \ appears in the end it raises error.

>>> r'so\m\e \te\xt'
'so\\m\\e \\te\\xt'

>>> r'so\m\e \te\xt\'
SyntaxError: EOL while scanning string literal

Update:

This is now covered in Python FAQs as well: Why can’t raw strings (r-strings) end with a backslash?

like image 310
Ashwini Chaudhary Avatar asked Jun 23 '12 08:06

Ashwini Chaudhary


1 Answers

You still need \ to escape ' or " in raw strings, since otherwise the python interpreter doesn't know where the string stops. In your example, you're escaping the closing '.

Otherwise:

r'it wouldn\'t be possible to store this string'
r'since it'd produce a syntax error without the escape'

Look at the syntax highlighting to see what I mean.

like image 111
Eric Avatar answered Sep 19 '22 10:09

Eric