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

How to split a string using multiple delimiters in PHP?

Split a string using preg_split

The preg_split function can split a string using regular expression. I demonstrate this in the below example:

<?php
$foo = "this/is\a-test_to-split=a-string-using?multiple_delimiters";
$res = preg_split("/(\/|\\\|-|_|\?|=)/", $foo);
print_r($res);
?>

Result:

Array
(
    [0] => this
    [1] => is
    [2] => a
    [3] => test
    [4] => to
    [5] => split
    [6] => a
    [7] => string
    [8] => using
    [9] => multiple
    [10] => delimiters
)

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

Split a string using explode along with str_replace

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

<?php

$foo = "this/is\a-test_to-split=a-string-using?multiple_delimiters";
$res=explode('\\',str_replace(array('/','-','_','?','='),'\\',$foo));
print_r($res);

?>

Result:

Array
(
    [0] => this
    [1] => is
    [2] => a
    [3] => test
    [4] => to
    [5] => split
    [6] => a
    [7] => string
    [8] => using
    [9] => multiple
    [10] => delimiters
)

In the above example, all the delimiters are replaced with \\, and then the same delimiter is used to split the string.