正则表达式用于拆分包含逗号的字符串

时间:2014-02-28 09:02:01

标签: python string split comma

我如何用逗号分割字符串,其中包含逗号本身?我们说字符串是:

object = """{"alert", "Sorry, you are not allowed to do that now, try later", "success", "Welcome, user"}"""

如何确保在分割后我只获得四个元素?

2 个答案:

答案 0 :(得分:5)

>>> from ast import literal_eval
>>> obj = '{"alert", "Sorry, you are not allowed to do that now, try later", "success", "Welcome, user"}'
>>> literal_eval(obj[1:-1])
('alert', 'Sorry, you are not allowed to do that now, try later', 'success', 'Welcome, user')

On Python3.2+您只需使用literal_eval(obj)

答案 1 :(得分:1)

>>> import re
>>> re.findall(r'\"(.+?)\"', obj)
['alert', 'Sorry, you are not allowed to do that now, try later',
 'success', 'Welcome, user']