gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:08:10 25 4
gpt4 key购买 nike

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

到目前为止我有:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com