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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap