Contents
Python – Split String by New Line
You can split a string in Python with new line as delimiter in many ways.
In this tutorial, we will learn how to split a string by new line character \n
in Python using str.split() and re.split() methods.
Examples
1. Split given string by new line using str.split()
In this example, we will take a multiline string string1
. We will call the split() method on this string with new line character \n
passed as argument. split() method splits the string by new line character and returns a list of strings.
Python Program
string1 = '''Welcome
to
pythonexamples.org'''
#split string by single new-line
chunks = string1.split('\n')
print(chunks)
Run Code Online Output
['Welcome', 'to', 'PythonExamples.org']
The string can also contain \n
characters in the string as shown below, instead of a multi-line string with triple quotes.
Python Program
str = 'Welcome\nto\nPythonExamples.org'
#split string by single new-line
chunks = str.split('\n')
print(chunks)
Run Code Online Output
['Welcome', 'to', 'PythonExamples.org']
2. Split given string by new line using re.split()
In this example, we will split the string by new line using split() method of regular expression re
package.
To use re
package, we have to import it at the start of our program.
Python Program
import re
string1 = '''Welcome
to
pythonexamples.org'''
#split string by single new-line
chunks = re.split('\n', string1)
print(chunks)
Run Code Online Output
['Welcome', 'to', 'pythonexamples.org']
3. Split given string by one or more newline characters
In this example, we will take a string with substrings separated by one or more new line characters. We will use re
package to split the string with one or more new line characters as delimiter. The regular expression that represents one or more new line characters is \n+
. We shall pass this expression and the string as arguments to re.split() method.
The syntax of re.split() method is re.split(regular_expression, string)
. The function returns list of substrings split from string
based on the regular_expression
.
Python Program
import re
str = '''Welcome
to
PythonExamples.org'''
#split string by one or more new-line
chunks = re.split('\n+', str)
print(chunks)
Run Code Online Regular Expression \n+
represents one or more adjacent new lines. So, one or more new lines is considered as a separator between splits.
Output
['Welcome', 'to', 'PythonExamples.org']
Summary
In this tutorial of Python Examples, we learned how to split a string by new line using String.split() and re.split() methods.