Python newline in string

In this article, I will show you how you can include newline characters in strings using python. Below are some ways that you can use to print new lines –

 

Python newline in string

 

Python newline in string

Like most programming languages, the newline character in python is represented as “\n”. It is used to indicate the end of a line of text and the start of a new line.

 

print("This is the first line.\nThis is the second line.")

 

And below is the python newline in string output –

This is the first line.
This is the second line.

 

You can also use the print() method to print a string and automatically add a newline character at the end of the string, like this:

 

Print("This is the first line.")
Print("This is the second line.")

 

You can also create a multiline string using the triple quotes like below –

multiline_str = """This is the first line.
This is the second line."""
print(multiline_str)

This will also have the same output as the below examples.

You can also create a newline string using the newline escape characters in combination with string concatenation + or using f-strings below are the examples –

strnewline = "This is the first line." + '\n' + "This is the second line."
print(strnewline)

OR

strnewline = f"This is the first line.{'\n'}This is the second line."
print(strnewline)

 

Both examples will output the same result as the first example

You can also use the str.join()” method to join multiple strings and insert a new line character between them.

 

linesArr = ["This is the first line.", "This is the second line."]
strnewline = "\n".join(linesArr)
print(strnewline)

 

This will also have the same output as the other examples.

One more way to add a new line in a string is using the “os.linesep” constant, which is platform-specific and returns the appropriate new line character for your operating system.

 

import os
strnewline = "This is the first line." + os.linesep + "This is the second line."
print(strnewline)

 

This is helpful if you’re developing code that will be run on different platforms and want to ensure that the newline character is always correct for the current platform.

 

Conclusion

These all are the possible ways to print python newline in string. I hope now you have some understanding of how to print a newline in a string using python.