Print a string raw (with escape characters) in Python

avatar

Borislav Hadzhiev

Last updated: Sep 3, 2022

banner

Photo from Unsplash

Print a string raw (with escape characters) in Python #

Use the repr() function to print a string raw, with escape characters, e.g. print(repr(my_str)). The repr() function returns a string containing a printable representation of the provided object.

main.py
my_str = 'one\ttwo\nthree' # ✅ Print a string with escape characters (repr()) print(repr(my_str)) # 👉️ 'one\ttwo\nthree' # ------------------------------------------------ # ✅ Convert string to bytes object with escape characters my_bytes = my_str.encode('unicode_escape') print(my_bytes) # 👉️ b'one\\ttwo\\nthree' # ------------------------------------------------ # ✅ Print a string with escape characters (encode() and decode()) result = my_str.encode('unicode_escape').decode() print(result) # 👉️ one\ttwo\nthree

The first example uses the repr() function to print the string raw, with escape sequences.

main.py
my_str = 'one\ttwo\nthree' print(repr(my_str)) # 👉️ 'one\ttwo\nthree'
The repr() function returns a printable representation of the provided object rather than the string itself.

If you have access to the variable's declaration, you can prefix the string with r to mark it as a raw string.

main.py
my_str = r'one\ttwo\nthree' print(my_str) # 👉️ one\ttwo\nthree
Strings that are prefixed with r are called raw strings and treat backslashes as literal characters.

If you need to interpolate a variable in a raw string, use a formatted string literal.

main.py
variable = 'two' my_str = fr'one\t{variable}\nthree' print(my_str) # 👉️ 'one\ttwo\nthree'

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Make sure to wrap expressions in curly braces - {expression}.

Notice that we prefixed the string with fr and not just with f.

Alternatively, you can use the str.encode() and bytes.decode() methods.

main.py
my_str = 'one\ttwo\nthree' my_bytes = my_str.encode('unicode_escape') print(my_bytes) # 👉️ b'one\\ttwo\\nthree' result = my_str.encode('unicode_escape').decode() print(result) # 👉️ one\ttwo\nthree

The str.encode method returns an encoded version of the string as a bytes object.

The bytes.decode method returns a string decoded from the given bytes. The default encoding is utf-8.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.