【问题标题】:split string on a number of different characters在多个不同的字符上拆分字符串
【发布时间】:2010-09-27 06:30:49
【问题描述】:

我想用一个或多个分隔符分割一个字符串。

例如"a b.c",拆分为 " " 和 "."将给出列表 ["a", "b", "c"]。

目前,我在标准库中看不到任何东西可以做到这一点,而且我自己的尝试有点笨拙。例如

def my_split(string, split_chars):
    if isinstance(string_L, basestring):
        string_L = [string_L]
    try:
        split_char = split_chars[0]
    except IndexError:
        return string_L

    res = []
    for s in string_L:
        res.extend(s.split(split_char))
    return my_split(res, split_chars[1:])

print my_split("a b.c", [' ', '.'])

太可怕了!有更好的建议吗?

【问题讨论】:

  • 那是“a b.c”(空格 b 点 c)吗?你有更多的样本输入吗?
  • 是的,没错。我已将问题更新为更清晰

标签: python string split


【解决方案1】:
>>> import re
>>> re.split('[ .]', 'a b.c')
['a', 'b', 'c']

【讨论】:

  • 请记住,字符必须放在方括号 [] 中。我忘记了这一点,至少浪费了 20 分钟。没有括号split() 根据整个字符串拆分。
【解决方案2】:

这个用列表中的第一个分隔符替换所有分隔符,然后使用该字符“拆分”。

def split(string, divs):
    for d in divs[1:]:
        string = string.replace(d, divs[0])
    return string.split(divs[0])

输出:

>>> split("a b.c", " .")
['a', 'b', 'c']

>>> split("a b.c", ".")
['a b', 'c']

不过,我确实喜欢那种“是”的解决方案。

【讨论】:

    【解决方案3】:

    无需回复的解决方案:

    from itertools import groupby
    sep = ' .,'
    s = 'a b.c,d'
    print [''.join(g) for k, g in groupby(s, sep.__contains__) if not k]
    

    解释在这里https://stackoverflow.com/a/19211729/2468006

    【讨论】:

      【解决方案4】:

      不是很快,但可以完成工作:

      def my_split(text, seps):
        for sep in seps:
          text = text.replace(sep, seps[0])
        return text.split(seps[0])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-21
        • 1970-01-01
        • 2014-08-31
        • 1970-01-01
        相关资源
        最近更新 更多