Python New Line – The New Line Character in Python

Python New Line

While printing some string to the output console screen or while adding content to files, people often require to have the text in a new line. A lot of people wonder how to add the text in a new line. Well, there a number of ways to specify a new line in different areas in python.

Python New Line Character

For most of the purposes, the newline character \n can be used to specify a new line. You can put this character within Python Strings. An example of using \n character in a string to display output to the console screen is given below.

name = "Gurmeet Singh \nWTMatter.com"
print(name)

Python New Line Character Usage

In the above example, the simply put the new line character \n right before the text which I want to be printed in the next line. Therefore it displays, the text before the newline character in the first line of output and the text written after in a new line. Likewise, you can use multiple newline characters in different ways of programming writing methods.

name = "Gurmeet Singh"
website = "WTMatter.com"
br = "\n"
print(name+br+website)

But most of the time, when printing the output to console, we use the print() function, which automatically, prints anything in a new line of the console output screen. To print the same output as above using only the print() function, the code will be as defined below.

print("Gurmeet Singh")
print("WTMatter.com")

Specifying New Lines in Python File Writing

We often need to add content to new lines while writing to files in python or any of the other programming languages.

f = open("file.txt", "w")
f.write("Line 1 Content")
f.write("\n")
f.write("Line 2 Content")
f.write("\n")
f.write("Line 3 Content")
f.close()

The following screenshot shows the text file output of the above python code, making use of new character \n to print text in new lines of the file created.

Python New Line In File Writing

Similarly, you can specify the newline character in a single line as well.

f = open("file.txt", "w")
f.write("Line 1 Content\nLine 2 Content\nLine 3 Content")
f.close()

Another New Line solution in Python File Writing is using the print statement similar to the console output.

f = open('file.txt', 'w')
print('Line 1 Content', file = f)
print('Line 2 Content', file = f)
print('Line 3 Content', file = f)
f.close()


Subscribe To WTMatter

Leave a Reply

Your email address will not be published. Required fields are marked *