将空格分隔的字符串转换为列表

我有一根这样的绳子:

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

我想把它分成这样一个列表

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

我是蟒蛇的新手。

请帮帮我

编辑: 我需要从状态中随机选择,并使它像变量一样。

894051 次浏览
states = "Alaska Alabama Arkansas American Samoa Arizona California Colorado"
states_list = states.split (' ')

Use string's split() method.

states.split()

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())
states_list = states.split(' ')

In regards to your edit:

from random import choice
random_state = choice(states_list)

try

states.split()

it returns the list

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

and this returns the random element of the list

import random
random.choice(states.split())

split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example

states.split('Ari')

returns

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

Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here

I see you are probably new to python, so I'd give you some advice how to use python's great documentation

Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language

I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this