引言
Python 字符串的 split
方法可以根据单个字符实现字符串的分割。
>>> s = 'a_b'
>>> s.split('_')
['a', 'b']
但对于如下特别复杂的字符串,如何根据多个字符实现字符串的分割?
- 样例输入
'a+b-c*d'
- 预期输出
['a', 'b', 'c', 'd']
对于该问题,需要搭配 Python 内置正则表达式模块 re
来使用。
>>> s = 'a+b-c*d'
>>> import re
>>> re.split('\+|-|\*', s)
['a', 'b', 'c', 'd']
注:+
和 *
有特殊含义,因此前面需要加上反斜杠,才能匹配本身;|
代表或的意思。
https://docs.python.org/3/library/re.html#re.split https://www.runoob.com/python/python-reg-expressions.html https://stackoverflow.com/questions/4998629/split-string-with-multiple-delimiters-in-python