How to split string with multiple delimiter ?

Posted by Afsal on 07-Oct-2022

Hello Pythonistas!

Today we are discussing a simple trick: how to split string with multiple delimiters.

We know that string.split(delimiter) is used for split string. But the issue is we can only use one delimiter. To split with multiple delimiters we are using the re module. Let us learn using an example. I want to separate a string with a comma or semi-colon

Code

import re
text = "hello,world;this is python"
split = re.split(',|;', a)
print(split)

Output

['hello', 'world', 'this is python']

Here |(pipe) symbol is used for OR condition. If I need to split using commas, semi-colon,s and space and another OR condition

Code

re.split(',|;| ', a)

Output

['hello', 'world', 'this', 'is', 'python']

Note: Don’t use re.split if there is only one delimiter instead use the string split method. split is much faster than re.split

Hope you have learned something from this post. Please share your valuable feedback with afsal@parseltongue.co.in