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 Python Strings. An example of using
\n the character in a string to display output to the console screen is given below.
name = "Gurmeet Singh \nCodeLucky.com" print(name)
In the above example, they 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 = "CodeLucky.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("CodeLucky.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 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()