Skip to content

Commit b95b1b3

Browse files
gh-55688: Add note about ending backslashes for raw strings (#94768)
Co-authored-by: hauntsaninja <[email protected]>
1 parent 5369bba commit b95b1b3

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Doc/faq/programming.rst

+40
Original file line numberDiff line numberDiff line change
@@ -1026,6 +1026,46 @@ What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
10261026
See the :ref:`unicode-howto`.
10271027

10281028

1029+
.. _faq-programming-raw-string-backslash:
1030+
1031+
Can I end a raw string with an odd number of backslashes?
1032+
---------------------------------------------------------
1033+
1034+
A raw string ending with an odd number of backslashes will escape the string's quote::
1035+
1036+
>>> r'C:\this\will\not\work\'
1037+
File "<stdin>", line 1
1038+
r'C:\this\will\not\work\'
1039+
^
1040+
SyntaxError: unterminated string literal (detected at line 1)
1041+
1042+
There are several workarounds for this. One is to use regular strings and double
1043+
the backslashes::
1044+
1045+
>>> 'C:\\this\\will\\work\\'
1046+
'C:\\this\\will\\work\\'
1047+
1048+
Another is to concatenate a regular string containing an escaped backslash to the
1049+
raw string::
1050+
1051+
>>> r'C:\this\will\work' '\\'
1052+
'C:\\this\\will\\work\\'
1053+
1054+
It is also possible to use :func:`os.path.join` to append a backslash on Windows::
1055+
1056+
>>> os.path.join(r'C:\this\will\work', '')
1057+
'C:\\this\\will\\work\\'
1058+
1059+
Note that while a backslash will "escape" a quote for the purposes of
1060+
determining where the raw string ends, no escaping occurs when interpreting the
1061+
value of the raw string. That is, the backslash remains present in the value of
1062+
the raw string::
1063+
1064+
>>> r'backslash\'preserved'
1065+
"backslash\\'preserved"
1066+
1067+
Also see the specification in the :ref:`language reference <strings>`.
1068+
10291069
Performance
10301070
===========
10311071

Doc/tutorial/introduction.rst

+5
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,11 @@ the first quote::
189189
>>> print(r'C:\some\name') # note the r before the quote
190190
C:\some\name
191191

192+
There is one subtle aspect to raw strings: a raw string may not end in
193+
an odd number of ``\`` characters; see
194+
:ref:`the FAQ entry <faq-programming-raw-string-backslash>` for more information
195+
and workarounds.
196+
192197
String literals can span multiple lines. One way is using triple-quotes:
193198
``"""..."""`` or ``'''...'''``. End of lines are automatically
194199
included in the string, but it's possible to prevent this by adding a ``\`` at

0 commit comments

Comments
 (0)