Summary: Use given_string.splitlines()
to split a given multiline string into multiple lines.
Minimal Example:
text = 'Python\nJava\nC#' print(text.splitlines()) # Output: ['Python', 'Java', 'C#']
Problem Formulation
📜Problem: Given a string, How will you split the string into a list of words using newline as a separator/delimiter?
Example:
# Input text = """abc def ghi """ # Expected Output ['abc', 'def', 'ghi']
Let’s dive into the different ways of solving the given problem.
Method 1: Using splitlines
Approach: The most convenient and easiest way to split a given multiline string into multiple strings is to use the splitlines()
method, i.e., simply use – 'given_string'.splitlines()
.
NOTE: splitlines()
is a built-in method in Python that splits a string at line breaks such as '\n'
and returns a split list of substrings (i.e., lines). For example, 'finxter\nis\ncool'.splitlines()
will return the following list: ['finxter', 'is', 'cool']
.
Code:
# Input text = """Python is an Object Oriented programming language. COBOL is an Object Oriented programming language. F# is an Object Oriented programming language.""" print(text.splitlines()) # Output: ['Python is an Object Oriented programming language.', 'COBOL is an Object Oriented programming language.', 'F# is an Object Oriented programming language.']
🌎Related Read: Python String splitlines()
Method 2: Using split()
Approach: Use 'given_string'.split('\n')
to split the given multiline string at line breaks.
Code:
# Input text = """Python is an Object Oriented programming language. COBOL is an Object Oriented programming language. F# is an Object Oriented programming language.""" print(text.split('\n')) # Output: ['Python is an Object Oriented programming language.', 'COBOL is an Object Oriented programming language.', 'F# is an Object Oriented programming language.']
Using “\n” ensures that whenever a new line occurs, the string is split.
🌎Related Read: Python String split()
Method 3: Using re.split in a List Comprehension
Another way to solve the given problem is to use the split method of the regex module. You can split the string at every line break by passing “\n” as the pattern within the re.split
function. To ensure that there are no leading or trailing extra whitespaces in the resultant list you can use a list comprehension that stores the split strings only and eliminates whitespace characters. This can be done with the help of an if statement within the list comprehension as shown in the solution below.
Code:
import re text = """Python is an Object Oriented programming language. COBOL is an Object Oriented programming language. F# is an Object Oriented programming language.""" print([x for x in re.split("\n", text) if x!='']) # Output: ['Python is an Object Oriented programming language.', 'COBOL is an Object Oriented programming language.', 'F# is an Object Oriented programming language.']
NOTE: The re.split(pattern, string)
method matches all occurrences of the pattern
in the string
and divides the string along the matches resulting in a list of strings between the matches. For example, re.split('a', 'bbabbbab')
results in the list of strings ['bb', 'bbb', 'b']
.
🌎Read more here – Python Regex Split
List Comprehension: “A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.”
🌎Read more here: List Comprehension in Python — A Helpful Illustrated Guide
Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.
Conclusion
We have successfully solved the given problem using three different approaches. I hope you this article answered all your queries. Please subscribe and stay tuned for more interesting articles!
Happy coding! 🙂
Related Reads:
⦿ Python | Split String by Newline
⦿ Python | Split String by Whitespace
⦿ Python | Split String into Characters
Python Regex Course
Google engineers are regular expression masters. The Google search engine is a massive text-processing engine that extracts value from trillions of webpages.
Facebook engineers are regular expression masters. Social networks like Facebook, WhatsApp, and Instagram connect humans via text messages.
Amazon engineers are regular expression masters. Ecommerce giants ship products based on textual product descriptions. Regular expressions rule the game when text processing meets computer science.
If you want to become a regular expression master too, check out the most comprehensive Python regex course on the planet: