[Tutor] Question about the raw string
Steven D'Aprano
steve at pearwood.info
Wed Nov 28 03:15:57 CET 2012
On Wed, Nov 28, 2012 at 01:01:12AM +0000, JiangShan wrote:
> Hi everyone,
>
> I am studying the python 3 and I am confused about the raw
> string. Why does the python interpreter do not escape the
> single backslash before the quotes even I add a "r" before the
> string. The following is an example:
>
> >>> print(r"\")
>
> SyntaxError: EOL while scanning string literal
> >>> print(r"\\")
> \\
> >>>
A very good question! Note that this is not just in Python 3, the same
thing applies to all versions of Python, and even other implementations
like IronPython:
steve at runes:~$ ipy
IronPython 2.6 Beta 2 DEBUG (2.6.0.20) on .NET 2.0.50727.1433
Type "help", "copyright", "credits" or "license" for more information.
>>> s = r"\"
File "<stdin>", line 1
s = r"\"
^
SyntaxError: EOL while scanning single-quoted string
Unfortunately, there is no good answer except "that's the way it is,
because that's the way the string parser is designed to work". It is a
documented limitation of raw strings:
http://docs.python.org/2/reference/lexical_analysis.html#string-literals
and it has been reported as a bug but closed as "Invalid":
http://bugs.python.org/issue1271
--
Steven
More information about the Tutor
mailing list