0

How do I print out my first three elemets in my tuple in a comma-seprated string (Im trying to learn: Dictionaries and Tuples, so I'm just playing around with it, thats why I've been converting it :) )

tup = ("snake", 89, 9.63, "bookshelf", 1)
list(tup)
tup[1] = "cow"
tuple(tup)
kreqq_
  • 43
  • 1
  • 9

2 Answers2

4

You slice the tuple then unpack it using *. Pass the sep parameter to print as comma ','

This does it:

>>> tup = ("snake", 89, 9.63, "bookshelf", 1)
>>> print(*tup[:3], sep=',')
snake,89,9.63

You can add some space in between the printed items if you add a trailing whitespace to the separator:

>>> print(*tup[:3], sep=', ')
snake, 89, 9.63

If you're looking to use the string in a value then join does exactly that:

>>> v = ', '.join(map(str, tup[:3]))
>>> v
'snake, 89, 9.63'
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Thanks! Everything runs perfect now, but what does join(map()) do? I mean a simple explanation about it so I understand it :) – kreqq_ Jul 19 '16 at 19:59
  • [`map`](https://docs.python.org/2/library/functions.html#map) works like a list comprehension. In this case, takes each item in the list and converts them to string. Then [`join`](http://stackoverflow.com/questions/1876191/explain-python-join) takes the new list of strings and performs a string concatenation with all the items – Moses Koledoye Jul 19 '16 at 20:01
0

Okey it dont quite work for me , I have a python file that have diffrent assignments where I learn dictionaries and tuples, and we answer by putting our answer in a variable called ANSWER and when I run the file it say if i completed the task or not.

This is what my answer looks like:

null <class 'NoneType'>

And this is the final code with your help:

tup = ("snake", 89, 9.63, "bookshelf", 1)
l = list(tup)
l[1] = "cow"
tuple(l)

ANSWER = print(*l[:3], sep=',')

And this is what the answer should look like

"snake,cow,9.63" <class 'str'>

What is that I have to change?

kreqq_
  • 43
  • 1
  • 9