2

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?

3
  • What version of python are you running? Commented Aug 4, 2014 at 15:52
  • 3
    You need to be certain that split() will return exactly three arguments, otherwise it's going to fail. Commented Aug 4, 2014 at 15:53
  • I am running Python 2.7.6 Commented Aug 4, 2014 at 15:57

4 Answers 4

5

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'
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

the above answer is correct also if you want to make a list do this:

   my_list=[first, second, third] = "alpha beta gamma".split()

Comments

-1

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

1 Comment

This list comprehension makes no sense, it just copies the elements from the list returned by split() into a new list, and then the list from split() is discarded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.