How to Print Strings with Newline (\n) Characters in Python?

Estimated read time 1 min read

To print strings with newline characters (\n) in Python, you can use the print function with the string as an argument. Whenever the print function encounters a newline character (\n) in a string, it will print the remaining characters on a new line. Here’s an example:

# Define a string with newline characters
string = "Hello\nWorld\n!"

# Print the string
print(string)

Output:

Hello
World
!

In this example, the string “Hello\nWorld\n!” contains two newline characters. When we pass this string to the print function, it prints each line on a new line, resulting in the output shown above.

You can also include other special characters in strings, such as tabs (\t) and backslashes (\), by escaping them with a backslash. For example:

# Define a string with tabs and backslashes
string = "This is a tab: \t and this is a backslash: \\"

# Print the string
print(string)

Output:

This is a tab:      and this is a backslash: \

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply