[python] How to print a single backslash?

When I write print('\') or print("\") or print("'\'"), Python doesn't print the backslash \ symbol. Instead it errors for the first two and prints '' for the second. What should I do to print a backslash?

This question is related to python escaping backslash

The answer is


You should escape it with another backslash \:

print('\\')

A backslash needs to be escaped with another backslash.

print('\\')

do you like it

print(fr"\{''}")

or how about this

print(r"\ "[0])

A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr:

>>> print(chr(92))
\

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to escaping

Uses for the '"' entity in HTML Javascript - How to show escape characters in a string? How to print a single backslash? How to escape special characters of a string with single backslashes Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence Properly escape a double quote in CSV How to Git stash pop specific stash in 1.8.3? In Java, should I escape a single quotation mark (') in String (double quoted)? How do I escape a single quote ( ' ) in JavaScript? Which characters need to be escaped when using Bash?

Examples related to backslash

How to print a single backslash? python replace single backslash with double backslash Escaping backslash in string - javascript File path issues in R using Windows ("Hex digits in character string" error) Replace "\\" with "\" in a string in C# How to remove backslash on json_encode() function? Java replace issues with ' (apostrophe/single quote) and \ (backslash) together How do I add slashes to a string in Javascript? String.replaceAll single backslashes with double backslashes Escaping Strings in JavaScript