简体   繁体   中英

Turn a string that is a formatted list into a list

I have a string

'[comedy, drama]'

that is a type str but appears to look like a list. Is there a quick change I can apply to turn it into a list with the two entries being both type str?

>>> '[comedy, drama]'[1:-1].split(', ')
['comedy', 'drama']

Quickest is

>>> s = '[comedy, drama]'
>>> s[1:-1].split(',')

Are the brackets and , part of the string? If so, you can just use str.split and str.strip .

s = '[comedy, drama, tragedy]'
wordList = s.replace(" ", "").strip("[]").split(",")

I have included s.replace(" ", "") so that it is agnostic as to whether they are split by ", " or by just ",", even mixed is fine.

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