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.
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.
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.
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())
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With