创建要在分隔符上拆分的函数

时间:2014-11-02 02:36:08

标签: python string python-3.x

此函数接受两个参数:text和separator,它们都是字符串,并返回文本中非空的非空字符串列表,通过在任何分隔符上拆分文本来确定。 separator是一串单字符分隔符。

以下是一个例子:

def split_on_separators(text, separators)
>>>split_on_separators("Hooray! Finally, we're done.", "!,")
['Hooray', ' Finally', " we're done."]

这是我到目前为止所做的:

    location_of_sep = []
    result = []
    for i in range(len(text)):
        if original[i] in separators:
            location_of_sep.append(i)

我被困在这部分之后。现在我有了分隔符的位置,如何将它添加到列表结果中。 我尝试了以下方法:

location_of_sep= [6, 15] #location of separator for the example given above
for j in location_of_sep:
    result.append(text[0:j])

这不起作用,因为它不会在两个分隔符之间获取文本。我可能在想这个。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:4)

如何使用re.split

>>> import re
>>> re.split("[!,]", "Hooray! Finally, we're done.")
['Hooray', ' Finally', " we're done."]

如果您不想使用正则表达式:

使用zip,你可以成对。

>>> text = "Hooray! Finally, we're done."
>>> location_of_sep = [6, 15]

>>> zip([-1] + location_of_sep, location_of_sep + [None])
[(-1, 6), (6, 15), (15, None)]

>>> [(i+1,j) for i, j in zip([-1] + location_of_sep, location_of_sep + [None])]
[(0, 6), (7, 15), (16, None)]

>>> [text[i+1:j] for i, j in zip([-1] + location_of_sep, location_of_sep + [None])]
['Hooray', ' Finally', " we're done."]