kreqq_
kreqq_

Reputation: 43

Python3 tuple and list, print out string comma-seperated

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)

Upvotes: 0

Views: 1413

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78564

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'

Upvotes: 5

kreqq_
kreqq_

Reputation: 43

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?

Upvotes: 0

Related Questions