我有一个字符串,需要在不使用正则表达式的情况下拆分为多个字符。例如,我需要如下内容:

>>>string="hello there[my]friend"
>>>string.split(' []')
['hello','there','my','friend']

在python中有这样的东西吗?

最佳答案

如果您需要多个分隔符,re.split是一种方法。
如果不使用正则表达式,除非为它编写自定义函数,否则不可能实现。
下面是这样一个函数-它可能做您想要的事情,也可能不做您想要的事情(连续的分隔符导致空元素):

>>> def multisplit(s, delims):
...     pos = 0
...     for i, c in enumerate(s):
...         if c in delims:
...             yield s[pos:i]
...             pos = i + 1
...     yield s[pos:]
...
>>> list(multisplit('hello there[my]friend', ' []'))
['hello', 'there', 'my', 'friend']

07-24 18:35
查看更多