Jacob Griffin
Jacob Griffin

Reputation: 5169

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.

Upvotes: 10

Views: 94052

Answers (3)

Bi Rico
Bi Rico

Reputation: 25833

This also works:

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

Upvotes: 34

Jack
Jack

Reputation: 760

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)) + ")"

Upvotes: 11

Fred
Fred

Reputation: 1021

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

Upvotes: 7

Related Questions