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)"
Share:
87,522
Jacob Griffin
Author by

Jacob Griffin

Updated on March 02, 2020

Comments

  • Jacob Griffin
    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
    Jacob Griffin about 12 years
    Why does the {} need to be in there?
  • Jacob Griffin
    Jacob Griffin about 12 years
    For instance, what if I just wanted it to be "Tuple (2, a, 5)" instead of "Tuple: (2, a, 5)" with a colon?
  • Fred
    Fred about 12 years
    @JacobGriffin, use a format string --> docs.python.org/library/stdtypes.html#str.format, try the code
  • Crast
    Crast about 12 years
    The {} 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
    Jacob Griffin about 12 years
    Yes, this is definitely the most straightforward way!
  • Jacob Griffin
    Jacob Griffin about 12 years
    Thanks, user :) Thank you Crast