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

程序员听说需求改了 程序员听到需求改了

糖果

糖果
LUA教程

Apache APISIX在SAE应用市场发布

Apache APISIX在SAE应用市场发布 Continue reading

APISIX后台管理路由创建接口

Published on December 06, 2019

Openresty Nginx Tengine添加动态so库

Published on October 11, 2019