我如何用逗号分割字符串,其中包含逗号本身?我们说字符串是:
object = """{"alert", "Sorry, you are not allowed to do that now, try later", "success", "Welcome, user"}"""
如何确保在分割后我只获得四个元素?
答案 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']