python - 使用分隔符变量在 Python 中拆分字符串

标签 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()

但它并没有删除分隔符

最佳答案

正则表达式解决方案(对我来说)似乎非常简单:

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', '']

关于python - 使用分隔符变量在 Python 中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14720912/

相关文章:

java - 如何在 Java 中将字符串子串到第二个点 (.)?

regex - Apache 强制某些 URL 使用 HTTP,而所有其他 URL 使用 https

regex - 正则表达式匹配除包含特定模式的单词以外的所有单词

Python:检查哪个元组项字符串以1结尾(如果它以1结尾)

python - 如何将 pandas DataFrame 拆分为多个 DataFrame?

c# - 帮助正则表达式。需要提取 `<A HREF`

java - 在java上使用正则表达式检索字符串

python - 有没有一种特殊的方法来抓取动态网站?

python - ImportError:无法导入名称 PunktWordTokenizer

python - imaplib 和带有空格的文件夹