Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to comment code blocks in Python that contain backslashes in strings?

A backslash in a Python string indicates the beginning of a control command, for e.g. text\n adds a new line after 'text'. If backslashes in strings shall not be interpreted as commands a r must precede the string. That is usually the case if the string contains a Windows directory, i.e. folder=r'C:\u'. However, if I want to comment several lines by """ I get an error

"""
folder=r'C:\u'
"""
(unicode error) 'unicodeescape' codec can't decode bytes in position 13-14: truncated \uXXXX escape

If I comment line by line by # then there is no error, however this method is not comfortable for commenting a whole block:

#folder=r'C:\u'

How to comment a whole a block of code that contains strings with backslashes?

Python 3.10.9, IPython 8.7.0, Spyder 5.4.2, Windows 10

Edit

I am not looking for answers or comments in the sense "Don't use Windows, use Linux!"

like image 390
granular_bastard Avatar asked Feb 04 '26 04:02

granular_bastard


1 Answers

You can add the r prefix to a triple-quoted docstring to make it a raw string literal:

r"""
folder=r'C:\u'
foo='bar'
"""

Excerpt from PEP-257:

Use r"""raw triple double quotes""" if you use any backslashes in your docstrings.

like image 187
blhsing Avatar answered Feb 07 '26 17:02

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!