How to Split String with Multiple Delimiters in Python
You can split a string with multiple delimiters in Python by using various functions
such as split()
, compile()
, and translate()
.
Method 1: split()
function
# import package
import re
x = "ABC;DE:XY,Z"
re.split(";|:|,", x)
Method 2: compile()
function
# import package
import re
x = "ABC;DE:XY,Z"
delims = re.compile(r";|:|,")
delims.split(x)
Method 3: translate()
function
x = "ABC;DE:XY,Z"
x_rep = x.translate(str.maketrans({';': ',', ':': ','}))
x_rep.split(",")
The following examples demonstrate how to use split()
, compile()
, and translate()
functions to split the string on multiple delimiters in Python.
Example 1: Split using split()
function
The following example shows how to split a string on multiple delimiters using the split()
function from re package.
# import package
import re
# example String
x = "ABC;DE:XY,Z"
# split string on multiple delimiters (;,:, and ,)
re.split(";|:|,", x)
# output
['ABC', 'DE', 'XY', 'Z']
In this example, we split the string by three delimiters (semicolon, colon, and comma) using the split()
function.
Example 2: Split using compile()
function
The following example shows how to split the string on multiple delimiters using a compile()
function from the re package.
# import package
import re
# example String
x = "ABC;DE:XY,Z"
# split string on multiple delimiters (;,:, and ,)
delims = re.compile(";|:|,")
delims.split(x)
# output
['ABC', 'DE', 'XY', 'Z']
In this example, we split the string by three delimiters (semicolon, colon, and comma) using the compile()
function.
Example 3: Split using translate()
function
The following example shows how to split a string on multiple delimiters using the translate()
function.
We will first replace the multiple delimeters to one common delimiter with the translate()
function and then will split the
string based on one common delimiter.
# import package
import re
# example String
x = "ABC;DE:XY,Z"
# split string on multiple delimiters (;,:, and ,)
x_rep = x.translate(str.maketrans({';': ',', ':': ','}))
x_rep.split(",")
# output
['ABC', 'DE', 'XY', 'Z']
In this example, we split the string by three delimiters (semicolon, colon, and comma) using translate()
and split()
functions.