Open In App

Split a string on multiple delimiters in Python

Last Updated : 18 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore various methods to split a string on multiple delimiters in Python. The simplest approach is by using re.split().

Using re.split()

The re.split() function from the re module is the most straightforward way to split a string on multiple delimiters. It uses a regular expression to define the delimiters.

Python
import re

s = "apple, banana; orange grape"

# Split using re.split
res = re.split(r'[;,\s]+', s)
print(res)

Output
['apple', 'banana', 'orange', 'grape']

Explanation:

  • [;,\s]+: This pattern matches one or more occurrences of a semicolon (;), comma (,), or whitespace (\s).
  • re.split: Splits the string wherever the pattern matches.

Let’s explore other methods to split a string on multiple delimiters:

Using translate() and split()

If the delimiters are fixed and limited to a set of characters then we can replace them with a single delimiter (like a space) using translate() and use split().

Python
s = "apple, banana; orange grape"

# Replace delimiters with a space and split
s = s.translate(str.maketrans({',': ' ', ';': ' '}))
res = s.split()
print(res)

Output
['apple', 'banana', 'orange', 'grape']

Explanation:

  • str.maketrans: Creates a translation map where , and ; are replaced by a space.
  • str.translate: Applies the translation map to the string.
  • str.split: Splits the string on whitespace

Chaining replace() and split()

This method is straightforward but less efficient for handling many delimiters.

Python
s = "apple, banana; orange grape"

# Replace each delimiter by chaining
s = s.replace(',', ' ').replace(';', ' ')

# split string on whitespace.
res = s.split()
print(res)

Output
['apple', 'banana', 'orange', 'grape']

Explanation:

  • Replace each delimiter with a space using replace().
  • Finally, split the string on whitespace.


Practice Tags :

Similar Reads