How to Split String with Multiple Delimiters in Python
There are multiple ways you can split a string or strings of multiple delimiters in Python.
- re.split(): With re.split() you can specify multiple patterns for the separator.
- string.replace() and string.split(): Python string replace() is a built-in function that returns the copy of the string where all occurrences of the substring are replaced with another substring. Python string split() is a built-in function that splits the string into the list.
In this example, we will only see the re.split() method as it is the most pythonic and easy way.
Before we go ahead, let’s see how to split the string using a single delimiter.
Split String with Single Delimiter
To split a string with a single delimiter, you can use the string.split() method. Python string split() is a built-in function that splits the string into the list.
str = "Hey, Copines is a good song" print(str.split(","))
['Hey', ' Copines is a good song']
In this example, we split the string from the comma which is a delimiter in the string.
Split String with Multiple Delimiters
To split the string with multiple delimiters in Python, use the re.split() method. The re.split() function splits the string by each occurrence of the pattern. A delimiter is a series of one or more characters used to define the boundary between separate, independent regions in plain text or other data streams.
import re str = "Hey, Copines is a good song; I like that song" print(re.split('; |, |\*|\n', str))
['Hey', 'Copines is a good song', 'I like that song']
The re.split() function target string as per the regular expression pattern and the matches are returned in the form of a list.
You can see from our example that the string contains various symbols like “,”, and “;”. We have split the string from these two delimiters using the re.split() method.
That is it for this tutorial.