使用Separator变量在Python中拆分字符串

时间:2013-02-06 03:18:43

标签: python regex

我正在尝试编写一个函数来拆分给定分隔符的字符串。我已经看到类似问题的答案,这些问题使用正则表达式来忽略所有特殊字符,但我希望能够传入一个分隔符变量。

到目前为止,我已经:

def split_string(source, separators): 
    source_list = source
    for separator in separators:
        if separator in source_list:
                source_list.replace(separator, ' ') 
    return source_list.split()

但它并没有删除分隔符

4 个答案:

答案 0 :(得分:5)

正则表达式解决方案(对我来说)似乎很容易:

import re
def split_string(source,separators):
    return re.split('[{0}]'.format(re.escape(separators)),source)

示例:

>>> import re
>>> def split_string(source,separators):
...     return re.split('[{0}]'.format(re.escape(separators)),source)
... 
>>> split_string("the;foo: went to the store",':;')
['the', 'foo', ' went to the store']

在这里使用正则表达式的原因是,如果你希望在你的分隔符中有' ',这仍然有用......


另一种选择(我认为我更喜欢),你可以使用多字符分隔符:

def split_string(source,separators):
    return re.split('|'.join(re.escape(x) for x in separators),source)

在这种情况下,多字符分隔符将作为某种非字符串可迭代(例如元组或列表)传递,但单个字符分隔符仍然可以作为单个字符串传递。

>>> def split_string(source,separators):
...     return re.split('|'.join(re.escape(x) for x in separators),source)
... 
>>> split_string("the;foo: went to the store",':;')
['the', 'foo', ' went to the store']
>>> split_string("the;foo: went to the store",['foo','st'])
['the;', ': went to the ', 'ore']

或者,最后,如果你想分割连续的分隔符:

def split_string(source,separators):
    return re.split('(?:'+'|'.join(re.escape(x) for x in separators)+')+',source)

给出:

>>> split_string("Before the rain ... there was lightning and thunder.", " .")
['Before', 'the', 'rain', 'there', 'was', 'lightning', 'and', 'thunder', '']

答案 1 :(得分:2)

问题在于source_list.replace(separator, ' ')不会修改source_list;它只返回一个修改过的字符串值。但是你没有对这个修改过的值做任何事情,所以它就丢失了。

你可以这样做:

source_list = source_list.replace(separator, ' ')

然后source_list将拥有修改后的版本。我对你的功能进行了一次更改,然后在测试时它完美地工作了。

答案 2 :(得分:2)

您忘记将source_list.replace(separator,'')的结果分配回source_list

查看此修改后的代码段

def split_string(source, separators): 
    source_list = source
    for separator in separators:
        if separator in source_list:
                source_list=source_list.replace(separator, ' ') 
    return source_list.split()

答案 3 :(得分:0)

你应该使用split解决问题,它不需要正则表达式,但你可以让它工作,你需要做什么。

在您的示例代码中,您不会重新分配。