Python Newline Character

Python Newline Character

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 text to a new line. Well, there are a number of ways to specify a new line in different areas in python.

Python New Line Character

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

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

In the above example, we 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 the 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 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 a new character \n to print text in new lines of the file created.

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()

Leave a Reply

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