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
    评论
Python,可以使用join()函数将数组转换为字符串。join()函数是字符串的一个方法,它将数组的元素连接成一个字符串,并使用指定的分隔符将它们分隔开来。你可以通过在数组名称之前使用指定的分隔符来调用join()函数。 例如,如果我们有一个名为arr的数组,我们可以使用以下代码将其转换为字符串: ``` arr = ['hello', 'world', 'python'] separator = ' ' string = separator.join(arr) print(string) # 输出: hello world python ``` 在这个例子,我们将数组arr的元素使用空格作为分隔符连接起来,然后将结果保存在字符串变量string。最后,我们使用print()函数将结果打印出来。请注意,join()函数只能用于字符串数组,如果数组存在非字符串元素,则需要先将其转换为字符串。 引用提供了split()方法的使用,该方法用于将字符串分割成数组。然而,你的问题是将数组转换为字符串,因此split()方法并不适用于这种情况。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Python数组转字符串互转详细操作](https://blog.csdn.net/mycocoo/article/details/115213445)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [python数组和字符串之间的转换](https://blog.csdn.net/myself360013139/article/details/110221155)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值