10

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.

3 Answers 3

34

This also works:

>>> s = "Tuple: " + str(tup)
>>> s
"Tuple: (2, 'a', 5)"
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is definitely the most straightforward way!
11

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

Comments

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

5 Comments

Why does the {} need to be in there?
For instance, what if I just wanted it to be "Tuple (2, a, 5)" instead of "Tuple: (2, a, 5)" with a colon?
@JacobGriffin, use a format string --> docs.python.org/library/stdtypes.html#str.format, try the code
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.
Thanks, user :) Thank you Crast

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.