Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore backslashes as escape characters in Python? [duplicate]

I know this is similar to many other questions regarding backslashes, but this deals with a specific problem that has yet to have been addressed. Is there a mode that can be used to completely eliminate backslashes as escape characters in a print statement? I need to know this for ascii art, as it is very difficult to find correct positioning when all backslashes must be doubled.

print('''
/\\/\\/\\/\\/\\
\\/\\/\\/\\/\\/
''')
\```
like image 740
Daniel Domingos Avatar asked Oct 26 '25 09:10

Daniel Domingos


1 Answers

Preface the string with r (for "raw", I think) and it will be interpreted literally without substitutions:

>>> # Your original
>>> print('''
... /\\/\\/\\/\\/\\
... \\/\\/\\/\\/\\/
... ''')

/\/\/\/\/\
\/\/\/\/\/

>>> # as a raw string instead
>>> print(r'''
... /\\/\\/\\/\\/\\
... \\/\\/\\/\\/\\/
... ''')

/\\/\\/\\/\\/\\
\\/\\/\\/\\/\\/

These are often used for regular expressions, where it gets tedious to have to double-escape backslashes. There are a couple other letters you can do this with, including f (for format strings, which act differently), b (a literal bytes object, instead of a string), and u, which used to designate Unicode strings in python 2 and I don't think does anything special in python 3.

like image 84
Green Cloak Guy Avatar answered Oct 28 '25 23:10

Green Cloak Guy