Split String in Python with Multiple Delimiters

If you have multiple delimiters in a string and you want to split them, the best way to deal with this is using the re module in Python.

Example:
import re

string_data = "part1,part2|part3,part4|part5"

split_list = re.split(r'\|', string_data)

final_list = [re.split(r',', item) for item in split_list]

print(final_list)
Output:
[['part1', 'part2'], ['part3', 'part4'], ['part5']]

In the above example we have two delimiters in the string, comma and pipe. We make use of the regular expression to first split the string based on the pipe, so we get a list of sub-strings that are now comma separated. Next, we make use of the regular expression to break these lists by commas and create a list-of-list.

Split String in Python with Multiple Delimiters

Reference documentation:

Python re module documentation: https://docs.python.org/3/library/re.html

Python re.split() function documentation: https://docs.python.org/3/library/re.html#re.split

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!