用多个字符分割字符串(python)[重复]

Ok so I know I can split a string using the .split method every time a character/a sequence of characters appears - for example, in the following code, when I use the .split method, the <string> is splitted every time : appears in it

<string>.split(":")

但是我不能给它提供多个参数,因此,如果出现其中一个参数,则字符串将被拆分。

例如,给定此输入字符串:

input_string = """ \ hel\lo ="world"""

I want to split the input_string every time \, =, ", or <blank space> appears, so that i get the following output:

['hel', 'lo', 'world']

我知道解决方案可能是:

non_alfanumeric = """\\=" """
input_string = """ \ hel\lo ="world"""

for char in non_alfanumeric:
    input_string = input_string.replace(char, " ")

list = input_string.split(" ")
while "" in list:
    list.remove("")

but this would be too much computationally slow if the input string is very long, because the code has to check the whole string 4 times: first time for \, second time for =, third time for ", fourth time for <blank space>.

还有什么其他解决方案?

评论
  • 竹Oo
    竹Oo 回复

    it seems that re.split will be good for your case.

  • 苍涼
    苍涼 回复

    您可能需要查看正则表达式拆分,例如

    import re
    
    [x for x in re.split(r'[ =: \\"]', """ \ hel\lo ="world""") if x]