11

我想使用一个或多个分隔符来拆分字符串。

例如“a bc”,拆分为“”和“。” 将给出列表 ["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", [' ', '.'])

可怕!有更好的建议吗?

4

4 回答 4

38
>>> import re
>>> re.split('[ .]', 'a b.c')
['a', 'b', 'c']
于 2008-12-17T02:16:43.560 回答
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']

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

于 2008-12-17T03:31:13.600 回答
2

没有重新的解决方案:

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

于 2013-10-06T17:41:01.830 回答
1

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

def my_split(text, seps):
  for sep in seps:
    text = text.replace(sep, seps[0])
  return text.split(seps[0])
于 2009-06-16T10:09:29.883 回答