Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Split a Multi-line String into Multiple Lines?

#1
How to Split a Multi-line String into Multiple Lines?

Rate this post

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:




https://www.sickgaming.net/blog/2022/12/...ple-lines/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python zip(): Get Elements from Multiple Lists xSicKxBot 0 1,967 08-26-2023, 01:28 AM
Last Post: xSicKxBot
  [Tut] Write a Long String on Multiple Lines in Python xSicKxBot 0 1,500 08-17-2023, 11:05 AM
Last Post: xSicKxBot
  [Tut] How to Access Multiple Matches of a Regex Group in Python? xSicKxBot 0 1,485 04-04-2023, 02:26 PM
Last Post: xSicKxBot
  [Tut] Python | Split String and Remove newline xSicKxBot 0 1,286 12-16-2022, 10:38 PM
Last Post: xSicKxBot
  [Tut] Python | Split Text into Sentences xSicKxBot 0 1,170 12-14-2022, 01:24 PM
Last Post: xSicKxBot
  [Tut] Python | Split String with Regex xSicKxBot 0 1,407 12-13-2022, 06:04 AM
Last Post: xSicKxBot
  [Tut] Python | Split String into List of Substrings xSicKxBot 0 1,435 12-11-2022, 12:17 PM
Last Post: xSicKxBot
  [Tut] Python | Split String Variable Spaces xSicKxBot 0 1,290 12-07-2022, 06:41 AM
Last Post: xSicKxBot
  [Tut] Python | Split String Multiple Whitespaces xSicKxBot 0 1,331 12-06-2022, 10:04 AM
Last Post: xSicKxBot
  [Tut] Python | Split String by Number xSicKxBot 0 1,148 12-05-2022, 01:21 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016