Python ProgrammingPython Programming

How to Split Strings on Multiple Delimiters or specified characters?

import re
 
 
string_test = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
print(re.findall(r"[\w']+", string_test))
 
def split_by_char(s, seps):
    res = [s]
    for sep in seps:
        s, res = res, []
        for seq in s:
            res += seq.split(sep)
    return res
 
print(split_by_char(string_test, [' ', '(', ')', ',']))
Sample output of above program.

['Ethnic', '279', 'Responses', '3', '2016', 'Census', '25', 'Sample']
['Ethnic', '', '279', '', '', 'Responses', '', '3', '', '', '2016', 'Census', '-', '25%', 'Sample']