To split a string by newline in Python, you can use the Python string split() function and pass ‘n’ to get a list of strings.
string = "This is anstring withnnewline in it"
print(string.split("n"))
#Output:
["This is a", "string with", "newline in it"]
You can also use the split() function from the re (regular expression) module.
import re
string = "This is anstring withnnewline in it"
print(re.split("n", string))
#Output:
["This is a", "string with", "newline in it"]
When working with strings and text in Python, the ability to manipulate and create new objects from strings can be useful.
One such situation is if you have newline characters in your strings and want to get the substrings between the newline characters.
To split a string by newline in Python, you can use the Python string split() function and pass ‘n’ to get a list of strings.
Below is a simple example showing you how you can use split() to split a string by newline into a list of strings.
string = "This is anstring withnnewline in it"
print(string.split("n"))
#Output:
["This is a", "string with", "newline in it"]
Splitting String by Newline with re.split() Function in Python
Another way you can split a string by the newline character is to use the regular expression module split() function to perform a regular expression which will find the “n” characters and then create a list of strings.
Below is a simple example showing you how you can use re.split() to split a string by newline into a list of strings in Python.
import re
string = "This is anstring withnnewline in it"
print(re.split("n", string))
#Output:
["This is a", "string with", "newline in it"]
Splitting String When There are More than One Newline in Python
Many times, you have more than one lines which you want to get rid of or deal with. With the re module, you can pass ‘n+’ to re.split() and split a string which has multiple newline characters.
Below is a simple example showing you how to split a string with multiple newline characters.
import re
string = "This is annstring withnnnnnewline in it"
print(re.split("n+", string))
#Output:
["This is a", "string with", "newline in it"]
Hopefully this article has been useful for you to learn how to split a string by newline in Python.