Skip to content

gh-55688: Add note about ending backslashes for raw strings #94768

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions Doc/faq/programming.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1019,6 +1019,46 @@ What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
See the :ref:`unicode-howto`.


.. _faq-programming-raw-string-backslash:

Can I end a raw string with an odd number of backslashes?
---------------------------------------------------------

A raw string ending with an odd number of backslashes will escape the string's quote::

>>> r'C:\this\will\not\work\'
File "<stdin>", line 1
r'C:\this\will\not\work\'
^
SyntaxError: unterminated string literal (detected at line 1)

There are several workarounds for this. One is to use regular strings and double
the backslashes::

>>> 'C:\\this\\will\\work\\'
'C:\\this\\will\\work\\'

Another is to concatenate a regular string containing an escaped backslash to the
raw string::

>>> r'C:\this\will\work' '\\'
'C:\\this\\will\\work\\'

It is also possible to use :func:`os.path.join` to append a backslash on Windows::

>>> os.path.join(r'C:\this\will\work', '')
'C:\\this\\will\\work\\'

Note that while a backslash will "escape" a quote for the purposes of
determining where the raw string ends, no escaping occurs when interpreting the
value of the raw string. That is, the backslash remains present in the value of
the raw string::

>>> r'backslash\'preserved'
"backslash\\'preserved"

Also see the specification in the :ref:`language reference <strings>`.

Performance
===========

Expand Down
5 changes: 5 additions & 0 deletions Doc/tutorial/introduction.rst
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,11 @@ the first quote::
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name

There is one subtle aspect to raw strings: a raw string may not end in
an odd number of ``\`` characters; see
:ref:`the FAQ entry <faq-programming-raw-string-backslash>` for more information
and workarounds.

String literals can span multiple lines. One way is using triple-quotes:
``"""..."""`` or ``'''...'''``. End of lines are automatically
included in the string, but it's possible to prevent this by adding a ``\`` at
Expand Down