Print string including newline (\n) characters in Python

avatar

Borislav Hadzhiev

Last updated: Sep 5, 2022

banner

Photo from Unsplash

Print string including newline (\n) characters in Python #

Use the repr() function to print a string including newline (\n) characters, e.g. print(repr(my_str)). The repr() function returns a string containing a printable representation of the provided object.

main.py
# ✅ print string including newline (\n) characters (repr()) my_str = 'bobby\nhadz' print(repr(my_str)) # 👉️ 'bobby\nhadz' # ---------------------------- # ✅ print string including newline (\n) characters (raw string) my_str = r'bobby\nhadz' print(my_str) # 👉️ bobby\nhadz

The first example uses the repr() function to print a string including the newline (\n) characters.

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'bobby\nhadz' print(my_str) # 👉️ bobby\nhadz
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
extension = '.com' my_str = fr'bobby\nhadz{extension}' print(my_str) # 👉️ bobby\nhadz.com
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.

If you have a multiline string, use a triple-quoted raw string.

main.py
my_str = 'bobby\nhadz\ncom' my_bytes = my_str.encode('unicode_escape') print(my_bytes) # 👉️ b'bobby\\nhadz\\ncom' result = my_str.encode('unicode_escape').decode() print(result) # 👉️ bobby\nhadz\ncom

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.

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.

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.