list items to its own variable
sentence = 'every good boy does fine'
This exercise asks to 'Store each word in a separate variable, then print out the sentence on one line using print.' After pondering for two hours, here's the best that I could come up with--
2 a = 'every'
3 b = 'good'
4 c = 'boy'
5 d = 'does'
6 e = 'fine'
7
8 together = a + b + c + d + e
9 print(together)
Is there an easier way to do this? Like
sentence = 'every good boy does fine'.split()
...then every item on that list is placed in its own variable; then from there, add all the variables together to piece back any sentence in a prescribed way(example--bcdae, or ecabd, etc.).
thanks for helping this noob!开发者_运维问答
Lists and other sequences can be unpacked like so:
a,b,c,d,e = 'every good boy does fine'.split()
If you add a *
before the last variable (e.g. *e
) then remaining elements that don't get unpacked can be accessed in the last variable as a list.
You could then print however you want:
>>> print(a,b,c,d,e)
every good boy does fine
>>> print(b,c,d,a,e)
good boy does every fine
You could do as proposed above
sentence = 'every good boy does fine'.split()
and then access each item in the list and put it into a variable.
a = sentence[0] b = sentence[1]
and so on.
Then print as you did in your example code above. Note that this approach of putting each word in its own variable only works if you know how many words are in the sentence before the program runs.
精彩评论