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

regex解决方案(对我来说)似乎非常简单:import re

def split_string(source,separators):

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

示例:

^{pr2}$

在这里使用regex的原因是如果您不想在分隔符中使用' ',这仍然有效。。。在

另一种选择(我想我更喜欢),您可以使用多字符分隔符:def split_string(source,separators):

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

在这种情况下,多字符分隔符作为某种非字符串iterable(例如元组或列表)传入,但单字符分隔符仍然可以作为单个字符串传入。在>>> 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', '']

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值