简体   繁体   中英

How can I split comma separated words wrapped in quotes efficiently in Python?

I've done some basic string parsing in python with split, and I currently have this type of output:

{"repositories":["docker1","myImage","repo123"]}

The "repositories" is guaranteed but the list may go on for hundreds. My first thought is to start at [17:-2] which would leave a comma separated list of quoted words, then split into a list by the commas, and then take each of those words [1:-1].

Is there a more 'elegant' solution to this?

That looks like JSON! Assuming it is...

>>> import json
>>> a = json.loads('{"repositories":["docker1","myImage","repo123"]}')
>>> a['repositories']
["docker1","myImage","repo123"]  # A python list, not a string

If it is guaranteed to be JSON, you can use the above method to convert the string directly into a Python object, obviating the need for any parsing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM