简体   繁体   中英

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)

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'

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM