How could I split a string by comma which contains commas itself in Python? Let's say the string is:
object = """{"alert", "Sorry, you are not allowed to do that now, try later", "success", "Welcome, user"}"""
How do I make sure I only get four elements after splitting?
>>> 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+ you can simply use literal_eval(obj)
.
>>> import re
>>> re.findall(r'\"(.+?)\"', obj)
['alert', 'Sorry, you are not allowed to do that now, try later',
'success', 'Welcome, user']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With