Table of Contents
In this post, we will see how to split String with multiple delimiters in Python.
Splitting a string in Python
When we talk about splitting a string, it means creating a collection of sub-strings out of a string. We can split a string by a character and create a list of sub-strings. In Python, we can split a string by single or multiple delimiter characters.
Ways to split a string in Python
We will now discuss how to split a string based on multiple delimiters in python.
Using the split()
and replace()
functions
We can use the split()
function to split a string based on some delimiter in Python. First, we will replace the second delimiter with the first delimiter using the replace()
function.
Then, we proceed to split the string using the first delimiter using the split()
function that will return a list of sub-strings.
See the code below.
1 2 3 4 5 6 |
a = "split, the; string, multiple, delimiters" a = a.replace(';',',') lst = a.split(',') print(lst) |
Output:
In the above example,
- We replace the
;
character with,
using thereplace()
function. - Then we split the string based on the
,
character using thestring()
function.
Using the regular expressions
Regular expressions are clean, compact patterns that can match parts of the strings. To use regular expressions in Python, we use the re
library.
We use the re.split()
to split the string based on the occurrence of some pattern. To split a string using multiple delimiters, we specify multiple delimiters in the pattern.
For example,
1 2 3 4 5 |
import re a = "split, the; string, multiple, delimiters" print(re.split('; |, ',a)) |
Output:
We can also use this function in another way. First, we will create a pattern using the re.compile()
function and then use it separately with the re.split()
function.
For example,
1 2 3 4 5 6 |
import re a = "split, the; string, multiple, delimiters" pattern = re.compile(r"[;,]") print(pattern.split(a)) |
Output:
This method is a good way to use regular expressions as it allows reusability of the pattern.