Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a space delimited string to list [duplicate]

Tags:

python

string

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.

like image 352
Hudec Avatar asked Nov 25 '11 08:11

Hudec


People also ask

How do I turn a string into a list of numbers?

Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.

How do I split a string into a list of words?

To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters.


2 Answers

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()) 
like image 114
eumiro Avatar answered Oct 05 '22 21:10

eumiro


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

like image 38
Jan Vorcak Avatar answered Oct 05 '22 23:10

Jan Vorcak