I have a string for items separated by comma. Each item is surrounded by quotes ("), but the items can also contain commas (,). So using split(',')
creates problems.
How can I split this text properly in Python?
"coffee", "water, hot"
["coffee", "water, hot"]
You can split on separators that contain more than one character. '"coffee", "water, hot"'.split('", "')
gives ['"coffee','water, hot"']
. From there you can remove the initial and terminal quote mark.
import ast
s = '"coffee", "water, hot"'
result = ast.literal_eval(f'[{s}]')
print(result)
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