Convert a string to a raw string in Python

avatar

Borislav Hadzhiev

Last updated: Sep 4, 2022

banner

Photo from Unsplash

Convert a string to a raw string in Python #

To convert a string to a raw string:

  1. Use the str.encode() method to convert the string to a bytes object.
  2. Use the str.decode() method to convert the bytes object to a raw string.
main.py
my_str = 'one\ttwo\nthree' print(repr(my_str)) # 👉️ 'one\ttwo\nthree' # ✅ Convert string to raw bytes object my_bytes = my_str.encode('unicode_escape') print(my_bytes) # 👉️ b'one\\ttwo\\nthree' # ---------------------------------------------- # ✅ Convert string to raw string result = my_str.encode('unicode_escape').decode() print(result) # 👉️ one\ttwo\nthree

We used the str.encode() method to convert the string to a bytes object with escape characters.

The str.encode method returns an encoded version of the string as a bytes object. The default encoding is utf-8.

main.py
my_str = 'one\ttwo\nthree' # 👇️ with escape characters my_bytes = my_str.encode('unicode_escape') print(my_bytes) # 👉️ b'one\\ttwo\\nthree' # 👇️ without escape characters my_bytes = my_str.encode() print(my_bytes) # 👉️ b'one\ttwo\nthree'

Notice that when we use the unicode_escape encoding, an extra backslash is added.

Use the bytes.decode() method to convert the bytes object to a string.

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

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

Encoding is the process of converting a string to a bytes object and decoding is the process of converting a bytes object to a string.

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.

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.