Here are four ways to split a string based on multiple delimiters in Python:
- Using re.split() method
- Using a custom function
- Using str.replace() and str.split() Methods
- Using translate() and maketrans() Methods
Method 1: Using re.split() method
The re.split() function uses a regular expression pattern, where each delimiter is separated by the pipe character (|), which represents an or condition in regular expressions.
Visual Representation
Example
import re
input_string = "Hello, Welcome-to_USA"
# Delimiters: comma, hyphen, and underscore
delimiters = ",|-|_"
# Splitting the string
split_string = re.split(delimiters, input_string)
print(split_string)
Output
['Hello', ' Welcome', 'to', 'USA']
Method 2: Using a custom function
The custom function(multi_split) splits a string based on any number of delimiters specified in a list. It iterates through each delimiter, sequentially splitting and reassembling the string into smaller parts.
Example
def multi_split(str, delimiters):
parts = [str]
for delim in delimiters:
new_parts = []
for part in parts:
new_parts.extend(part.split(delim))
parts = new_parts
return parts
input_string = "Hello, Welcome-to_USA"
# Delimiters: comma, hyphen, and underscore
delimiters = [",", "-", "_"]
split_string = multi_split(input_string, delimiters)
print(split_string)
Output
['Hello', ' Welcome', 'to', 'USA']
Method 3: Using str.replace() and str.split()
First, replace the delimiters with spaces (‘ ‘) using the replace() method. Then, split the string into a list of substrings using the split() method.
Example
import re
input_string = "Hello, Welcome!to;USA"
# Delimiters: comma, exclamation mark, and semicolon
delimiters = [",", "!", ";"]
# Replace each delimiter in the string with a space
for delim in delimiters:
input_string = input_string.replace(delim, " ")
# Split the modified string into a list of words
split_string = input_string.split()
# Print the result splitting the string on multiple delimiters
print(split_string)
Output
['Hello', 'Welcome', 'to', 'USA']
Method 4: Using translate() and maketrans() Methods
First, create a translation table using maketrans(), mapping each delimiter to a space. Then, use translate() to replace each delimiter in the original string with a space. Finally, split the translated string into a list of substrings using split().
Example
input_string = "Hello, Welcome-to_USA"
# Delimiters: comma, hyphen, and underscore
delimiters = ", -, _"
# Create a translation table mapping each delimiter to a space
trans_table = str.maketrans(delimiters, ' ' * len(delimiters))
# Translate the string, replacing each delimiter with a space
translated_string = input_string.translate(trans_table)
# Split the translated string
split_string = translated_string.split()
print(split_string)
Output
['Hello', 'Welcome', 'to', 'USA']