如何在Python中按逗号切分包含逗号的字符串?假设字符串为:
object = """{"alert", "Sorry, you are not allowed to do that now, try later", "success", "Welcome, user"}"""
如何确保我在拆分后只获得四个元素?
>>> 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')
literal_eval(obj)
。
ValueError
异常,而 Python 3.3 可以识别。 - falsetru>>> import re
>>> re.findall(r'\"(.+?)\"', obj)
['alert', 'Sorry, you are not allowed to do that now, try later',
'success', 'Welcome, user']