Split string with multiple delimiters in Python

You can use the re.split() function from the re module in Python to split a string using multiple delimiters. The re.split() function takes two arguments: the pattern to split on (specified as a regular expression), and the string to split. Here's an example code snippet:

import re

# The string to split
s = "foo,bar:baz;qux"

# The delimiters to split on
delimiters = ",:;"

# Create a regular expression pattern from the delimiters
pattern = "|".join(map(re.escape, delimiters))

# Split the string using the pattern
result = re.split(pattern, s)

print(result)
# Output: ['foo', 'bar', 'baz', 'qux']

Watch a course Python - The Practical Guide

In this example, the delimiters variable is a string containing the characters that you want to use as delimiters. The re.escape() function is used to escape any special characters in the delimiters so that they are treated as literal characters when creating the regular expression pattern. The "|".join() method is used to join the escaped delimiters with the "or" operator (|) to create the pattern. The re.split() function is then used to split the input string s using this pattern, resulting in a list of substrings that are separated by the specified delimiters.