Split a string with multiple delimiters in Python

avatar

Borislav Hadzhiev

Last updated: Jun 24, 2022

banner

Photo from Unsplash

Split a string with multiple delimiters in Python #

To split a string with multiple delimiters:

  1. Import the re module.
  2. Use the re.split() method, e.g. re.split(r',|-', my_str_2).
  3. The re.split() method will split the string on all occurrences of one of the delimiters.
main.py
import re # 👇️ split string with 2 delimiters my_str = 'one,two-three,four' my_list = re.split(r',|-', my_str) # 👈️ split on comma or hyphen print(my_list) # 👉️ ['one', 'two', 'three', 'four'] # ------------------------------------------------------ # 👇️ split string with 3 delimiters my_str_2 = 'one,two-three:four' my_list_2 = re.split(r',|-|:', my_str_2) # 👈️ comma, hyphen or colon print(my_list_2) # 👉️ ['one', 'two', 'three', 'four']

The re.split method takes a pattern and a string and splits the string on each occurrence of the pattern.

The pipe | character is an OR. Either match A or B.

The first example splits the string using 2 delimiters - a comma and a hyphen.

The second example splits the string with 3 delimiters - a comma, a hyphen and a colon.

You can use as many | characters as necessary in your regular expression.

Alternatively, you can use square brackets [] to indicate a set of characters.

main.py
import re my_str = 'one,two-three,four' my_list = re.split(r'[,-]', my_str) print(my_list) # 👉️ ['one', 'two', 'three', 'four']

Make sure to add all of the delimiters between the square brackets.

main.py
import re # 👇️ split string with 3 delimiters my_str = 'one,two-three:four' my_list = re.split(r'[,-:]', my_str) print(my_list) # 👉️ ['one', 'two', 'three', 'four']

An alternative approach is to use the str.replace() method.

To split a string with multiple delimiters:

  1. Use the str.replace() method to replace the first delimiter with the second.
  2. Use the str.split() method to split the string by the second delimiter.
main.py
my_str_2 = 'one_two!three_four' my_list = my_str_2.replace('_', '!').split('!') print(my_list) # 👉️ ['one', 'two', 'three', 'four']
This approach is only convenient when you have few delimiters you want to split on, e.g. 2.

First, we replace every occurrence of the first delimiter with the second, and then we split on the second delimiter.

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

Note that the method doesn't change the original string. Strings are immutable in Python.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.