Python多分隔符号拆分字符串
如下代码,实现python多个分隔符拆分字符串。
def tsplit(string, delimiters):
"""Behaves str.split but supports multiple delimiters."""
delimiters = tuple(delimiters)
stack = [string,]
for delimiter in delimiters:
for i, substring in enumerate(stack):
substack = substring.split(delimiter)
stack.pop(i)
for j, _substring in enumerate(substack):
stack.insert(i+j, _substring)
return stack
很多时候我们需要用多个分隔符拆分字符串,例如拆分标签时,既要用中文的分号,也要用到英文的分号。
如下是使用方法:
>>> s = 'thing1,thing2/thing3-thing4'
>>> tsplit(s, (',', '/', '-'))
['thing1', 'thing2', 'thing3', 'thing4']
感谢作者分享:
http://outofmemory.cn/code-snippet/814/python-use-duoge-separator-chaifen-string
程序员听说需求改了