Python: Converting from Tuple to String?
87,522
Solution 1
This also works:
>>> s = "Tuple: " + str(tup)
>>> s
"Tuple: (2, 'a', 5)"
Solution 2
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)) + ")"
Solution 3
>>> tup = (2, "a", 5)
>>> s = "Tuple: {}".format(tup)
>>> s
"Tuple: (2, 'a', 5)"
Author by
Jacob Griffin
Updated on March 02, 2020Comments
-
Jacob Griffin about 4 years
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.
-
Jacob Griffin about 12 yearsWhy does the {} need to be in there?
-
Jacob Griffin about 12 yearsFor instance, what if I just wanted it to be "Tuple (2, a, 5)" instead of "Tuple: (2, a, 5)" with a colon?
-
Fred about 12 years@JacobGriffin, use a format string --> docs.python.org/library/stdtypes.html#str.format, try the code
-
Crast about 12 yearsThe
{}
is a format specifier, look up how python string formatting works. It means to interpolate a passed argument to the string. Since there's only one of these, it specifically means the first argument. -
Jacob Griffin about 12 yearsYes, this is definitely the most straightforward way!
-
Jacob Griffin about 12 yearsThanks, user :) Thank you Crast