简体   繁体   中英

How to convert list which contains a single string with multiple entries inside of string. Python 3

Let's say you have a list, which contains a single string as:

listExample = ['cat, dog, mouse, elephant']

So printing this list return the values as a single string:

>>>'cat, dog, mouse, elephant'

How do you get this string to the point where you can get the entries as multiple strings, such as:

>>>print(anotherList)
>>>['cat', 'dog', 'mouse', 'elephant']

You are describing the basic usage of str.split :

>>> listExample = ['cat, dog, mouse, elephant']
>>> listExample[0].split(', ')
['cat', 'dog', 'mouse', 'elephant']

You should use the split method. So do

'cat, dog, mouse, elephant'.split(', ')

this will give you

['cat', 'dog', 'mouse', 'elephant']

The ', ' means the string should be split every time there is a comma and then a space.

The list is not needed, but if you absolutely have to use the list then do

listExample[0].split(', ')

to get the string out of the list and then split it.

For more information see this

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