Advertisement
Advertisement


Convert a space delimited string to list


Question

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.

2019/07/30
1
99
7/30/2019 9:29:17 PM


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

2011/11/25

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

states_list = states.split(' ')

In regards to your edit:

from random import choice
random_state = choice(states_list)
2011/11/25

Use string's split() method.

states.split()
2011/11/25

Source: https://stackoverflow.com/questions/8266529
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]