To add a new line to a String in Python, add “\n” between the string characters where you want the new line to be inserted. I’ll show you several methods for adding a new line to the string.
So, Let’s see the various method and code examples on how to add a new line to a string in Python.
1. Using Universal Newline To Add A New Line To A String
The Unix end-of-line convention ‘\n’, the Windows convention ‘\r\n’, and the old Macintosh convention ‘\r’ are all recognized as ending a line in this interpretation. A newline(\n) character can be used to break up a multiline string, as shown in the example below.
In a multiline string, we can easily use the character ‘\n’ before each string that we want to display on a new line in a new line. Let us see the code example below.
#Initializing the String strToSplit = "You Are On Coduber.\nLearn To Code on This Website." #Printing the Above String print(strToSplit)
You Are On Coduber. Learn To Code on This Website.
2. Using splitlines() Function In Python
In Python, you can use the splitlines() function to split a string into a list and then print each list item in a new line without using the “\n” character in the print function or inside the string.
Return a list of the lines contained within the string, with line breaks occurring at line boundaries. Unless the option keepends is specified and set to true, line breaks are not included in the resulting list.
Let’s look at a Python code example for using the splitlines() function to print a new line in a string.
#Initializing the String strToSplit = "Split\r\nThe\rLine\rOne\r\nBy\nOne" splitLines = strToSplit.splitlines() #Printing the Above String for line in splitLines: print(line)
Split The Line One By One
With the help of the splitlines() function in Python, I was able to print all of the new lines in a string at once, as you can see in the example code above.
I hope you have gained an understanding of how to insert a new line into a string in Python. The most basic and commonly used method is the addition of “n” to the end of the string, which allows you to have a new line printed from the point at which the “n” is added to the end of the string.
If you know of a better method than the one discussed above, please let me know in the comments section and I will be happy to include it here.