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 and include the newline character in the string using the escape character \. Here’s an example code snippet that shows how to print strings with newline characters:

# Define a string with newline characters
my_string = 'Hello,\nWorld!'

# Print the string
print(my_string)

In this example, the code defines a string my_string that includes a newline character after the word ‘Hello’. To include the newline character in the string, it uses the escape character \ followed by the letter n. The resulting string includes a newline character, which causes the print() function to print the string on two separate lines.

You can include multiple newline characters in a string to print it on multiple lines. For example:

# Define a string with multiple newline characters
my_string = 'Line 1\n\nLine 2\n\n\nLine 3'

# Print the string
print(my_string)

In this example, the code defines a string my_string that includes multiple newline characters. When the string is printed using the print() function, it is printed on multiple lines with blank lines between each line.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply