Python中split()函数如何指定多个分隔符?

4
如何在Python中指定多个分隔符进行split()操作?
input = "print{hello world};x = 2 + 3;"
x = input.split('{') #this works but not the desired OP
x = input.split('{','}') #error 
x = input.split('{}') #this works but not the desired OP

期望的结果:

['print', 'hello world', ';x = 2 + 3;']

1
对于这种情况,您可以使用 re.split。 - Dani Mesejo
input.replace('}', '{').split('{') - Kelly Bundy
1
请您在问题中添加期望的输出。您可以在此处[编辑]您的问题。 - Ch3steR
我认为正则表达式是为此目的而设计的,而不是同时分割。 - sahasrara62
1个回答

4

您可以这样使用re.split

import re

my_input = "print{hello world};x = 2 + 3;"
re.split('{|}', my_input)

输出:

['print', 'hello world', ';x = 2 + 3;']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接