Convert a space delimited string to list

Hudec picture Hudec · Nov 25, 2011 · Viewed 893.1k times · Source

i have a string like this :

states = "Alaska Alabama Arkansas American Samoa Arizona California Colorado"

and I want to split it into a list like this

states = {Alaska, Alabama, Arkansas, American, Samoa, ....}

I am new in python.

Help me, please. :-))

edit: I need to make a random choice from states and make it like the variable.

Answer

eumiro picture eumiro · Nov 25, 2011

states.split() will return

['Alaska',
 'Alabama',
 'Arkansas',
 'American',
 'Samoa',
 'Arizona',
 'California',
 'Colorado']

If you need one random from them, then you have to use the random module:

import random

states = "... ..."

random_state = random.choice(states.split())