Reputation: 24111
I have a string myString
:
myString = "alpha beta gamma"
I want to split myString
into its three words:
myWords = myString.split()
Then, I can access each word individually:
firstWord = myWords[0]
secondWord = myWords[1]
thirdWord = myWords[2]
My question: How can I assign these three words in just one line, as an output from the split()
function? For example, something like:
[firstWord secondWord thirdWord] = myString.split()
What's the syntax in Python 2.7?
Upvotes: 2
Views: 12388
Reputation: 5514
To expand on Mr. Pieter's answer and the comment raised by TheSoundDefense,
Should str.split()
return more values than you allow, it will break with ValueError: too many values to unpack
. In Python 3 you can do
first, second, third, *extraWords = str.split()
And this will dump everything extra into a list called extraWords
. However, for Python 2 it gets a little more complicated and less convenient as described in this question and answer.
Alternatively, you could change how you're storing the variables and put them in a dictionary using a comprehension.
>>> words = {i:word for i,word in enumerate(myString.split())}
>>> words
{0: 'alpha', 1: 'beta', 2: 'gamma'}
This has the advantage of avoiding the value unpacking all together (which I think is less than ideal in Python 2). However, this can obfuscate the variable names as they are now referred to as words[0]
instead of a more specific name.
Upvotes: 1
Reputation: 107287
the above answer is correct also if you want to make a list do this:
my_list=[first, second, third] = "alpha beta gamma".split()
Upvotes: 0
Reputation: 9
Alternatively, using a list comprehension ...
mystring = "alpha beta gamma"
myWords = [x for x in mystring.split()]
first = myWords[0]
second = myWords[1]
third = myWords[2]
print(first, second, third)
alpha beta gamma
Upvotes: -1
Reputation: 1121196
Almost exactly what you tried works:
firstWord, secondWord, thirdWord = myString.split()
Demo:
>>> first, second, third = "alpha beta gamma".split()
>>> first
'alpha'
>>> second
'beta'
>>> third
'gamma'
Upvotes: 5