How to Print a String Raw (with Escape Characters) in Python?

Estimated read time 1 min read

If you want to print a string raw, including any escape characters, you can use a raw string literal. In Python, a raw string literal is denoted by placing an r character before the opening quote of a string. Here’s an example:

my_string = r"Hello\nWorld!"
print(my_string)

Output:

Hello\nWorld!

In the above example, the r character before the opening quote indicates that the string should be treated as a raw string. The escape character \n in the string is not interpreted as a newline character, but rather as a literal backslash followed by the letter n. When the string is printed to the console using the print() function, the escape character \n is displayed as a literal \ followed by the letter n.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply