python在没有正则表达式的多个分隔符上拆分字符串

ewo*_*wok 3 python string split

我有一个字符串,我需要拆分多个字符而不使用正则表达式.例如,我需要以下内容:

>>>string="hello there[my]friend"
>>>string.split(' []')
['hello','there','my','friend']
Run Code Online (Sandbox Code Playgroud)

像python这样的东西有什么?

Thi*_*ter 6

如果你需要多个分隔符,那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']
Run Code Online (Sandbox Code Playgroud)