How to split a string using multiple delimiters in Python?

In this post, I present two ways to split a string using multiple delimiters in Python.

Split a string using regular expression

Regular expressions are very powerful. It helps to get things done with a single function call. In the below example I use the split function from the re library to split a string along with multiple delimiters:

import re
str="this-is_an=example\string"
re.split(r"[-_=\\]", str)

Result:

['this', 'is', 'an', 'example', 'string']

In the above example, the string is split along the \, -, _, and = delimiters.

Replace other delimiters and split it

Another solution is to choose a single delimiter and replace all the other delimiters with the chosen one. After that, the split function can be used. I demonstrate this in the below example:

str="this-is_an=example\\string"
delimiters = ['-', '_', '=', '\\']
for i in range(1, len(delimiters)):
    str = str.replace(delimiters[i], delimiters[0])

str.split(delimiters[0])

Result:

['this', 'is', 'an', 'example', 'string']

In the above example, first I replaced all the delimiters with -, and then I used the same delimiter to split the string.

Demonstration video

Leave a Reply