Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

python - 将空格分隔的字符串转换为列表[重复](Convert a space delimited string to list [duplicate])

Possible Duplicate:

(可能重复:)
String to list in Python

(要在Python中列出的字符串)

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.

(我是python的新手。)

Help me, please.

(请帮帮我。)

:-))

(:-)))

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

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

  ask by Hudec translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

states.split() will return

(states.split()将返回)

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

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

(如果你需要一个随机,那么你必须使用random模块:)

import random

states = "... ..."

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...