0. References

Why can’t Python’s raw string literals end with a single backslash?


Phenomenon of 1.

Python’s raw strings have many applications, such as to represent Windows paths and to be used in regular expressions. But when used, it turns out that the original string cannot end with a single backslash, or an odd number of backslashes. Try this:

>>> r'\' File "", line 1 r'\' ^ SyntaxError: EOL while scanning string literal >>> r'\ \ \' File "", line 1 r'\ \ \' ^ SyntaxError: EOL while scanning string literalCopy the code

2. Explain

The most common misconception is that a backslash in the original string is no different from any other character. This is wrong!

When r or the prefix r is present, the characters following the backslash remain the same, and the backslash itself remains in the string.

So anything that comes after a backslash is part of the original string. In this way:

  • r'abc\d'a, b, c, \, dcomposition
  • r'abc\'d'a, b, c, \, ', dcomposition
  • r'abc\''a, b, c, \, 'composition

So here’s the point:

  • r'abc\'a, b, c, \, 'Composition, but nowThere are no ending quotes!

So the original string cannot end with a single (odd) backslash.


3. Solve

Method 1

Instead of writing a single backslash after the original string, you use concatenation to add a backslash to a normal string.

>>> test = R 'test''\ \'
>>> printTest \ (test)Copy the code

Way 2

Write two backslashes after the original string, then slice off the last backslash.

>>> test = R 'test \ \'[: -1]
>>> printTest \ (test)Copy the code

Methods 3

Instead of using raw strings, use normal strings.

>>> test = 'test \ \'
>>> printTest \ (test)Copy the code

Completed in 201810290705