当前位置:  首页>> 技术小册>> Python合辑4-130个字符串操作示例

在多个分隔符或指定字符上拆分字符串

  1. import re
  2. string_test = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
  3. print(re.findall(r"[\w']+", string_test))
  4. def split_by_char(s, seps):
  5. res = [s]
  6. for sep in seps:
  7. s, res = res, []
  8. for seq in s:
  9. res += seq.split(sep)
  10. return res
  11. print(split_by_char(string_test, [' ', '(', ')', ',']))

Output:

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