Convert a space delimited string to list

PythonString

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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())

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

states_list = states.split(' ')

In regards to your edit:

from random import choice
random_state = choice(states_list)

Solution 5 - Python

Use string's split() method.

states.split()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHudecView Question on Stackoverflow
Solution 1 - PythoneumiroView Answer on Stackoverflow
Solution 2 - PythonJan VorcakView Answer on Stackoverflow
Solution 3 - PythonTimofey StolbovView Answer on Stackoverflow
Solution 4 - PythonKaiView Answer on Stackoverflow
Solution 5 - PythonMBoberView Answer on Stackoverflow