Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

How to join two tuples into a string?

I have two tuples, one being stored in the variable n, and the other stored in x. I want to join then together into one, final variable that is a string. How can I do this? I tried this but it did not work:

final = "".join(n) + "".join(str(x))

I am stringing x because it says it can't add STR and INT together

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The shortest answer would be

add n to tuple the convert
final = “”.join(x+(str(n),))
# or simple concatenation 
final = “”.join(x) + str(n)
# or f-string
final = f{‘’.join(x)}{n}

If x and n are both tuples and some values in both tuples are not strings, there are three steps:

  1. join tuples
  2. Convert to strings
  3. Join strings
Final = “”.join([str(item)
                 for item in x+n])

When I print it out, there are a bunch commas and parentheses:

(2, 3, 7) ('a', 'a', 'a', 'a', 'a', 'a')
Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

I’ve updated my answer. It might help recommend a specific solution if a sample x and n values are provided.

Thank you! I got it to work.

It also says:

TypeError: sequence item 0: expected str instance, int found

Am I doing something wrong?