简体   繁体   中英

Python: Converting from Tuple to String?

let's say that I have string:

    s = "Tuple: "

and Tuple (stored in a variable named tup):

    (2, a, 5)

I'm trying to get my string to contain the value "Tuple: (2, a, 5)". I noticed that you can't just concatenate them. Does anyone know the most straightforward way to do this? Thanks.

This also works:

>>> s = "Tuple: " + str(tup)
>>> s
"Tuple: (2, 'a', 5)"

Try joining the tuple. We need to use map(str, tup) as some of your values are integers, and join only accepts strings.

s += "(" + ', '.join(map(str,tup)) + ")"
>>> tup = (2, "a", 5)
>>> s = "Tuple: {}".format(tup)
>>> s
"Tuple: (2, 'a', 5)"

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