TypeError: can only concatenate str (not "tuple") to str


Borislav Hadzhiev

Wed Apr 20 20222 min read

TypeError: can only concatenate str (not "tuple") to str #

The Python "TypeError: can only concatenate str (not "tuple") to str" occurs when we try to concatenate a string and a tuple. To solve the error, access the tuple at a specific index to concatenate two strings, or use a formatted string literal.

typeerror can only concatenate str not tuple to str

Here is an example of how the error occurs.

my_str = 'fruits' my_tuple = ('apple', 'banana', 'kiwi') # ⛔️ TypeError: can only concatenate str (not "tuple") to str print(my_str + my_tuple)
We tried to use the addition (+) operator to concatenate a string and a tuple which caused the error.

The values on the left and right-hand sides need to be of compatible types.

If you only need to print the contents of the tuple, use a comma between the string and the tuple.

my_str = 'fruits' my_tuple = ('apple', 'banana', 'kiwi') print(my_str, my_tuple) # 👉️ fruits ('apple', 'banana', 'kiwi')

Alternatively, you can use a formatted string literal.

my_str = 'fruits' my_tuple = ('apple', 'banana', 'kiwi') result = f'{my_str} {my_tuple}' # 👇️ fruits ('apple', 'banana', 'kiwi') print(result)
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Make sure to wrap expressions in curly braces - {expression}.

If you meant to concatenate the string and a specific item of the tuple, access the tuple at the specific index.

my_str = 'fruit: ' my_tuple = ('apple', 'banana', 'kiwi') result = my_str + my_tuple[0] print(result) # 👉️ fruit: apple

We accessed the tuple item at index 0, which is a string, so we were able to concatenate the two strings.

You can also convert the tuple to a string by passing it to the str() class.

my_str = 'fruits: ' my_tuple = ('apple', 'banana', 'kiwi') # 👇️ convert tuple to str result = my_str + str(my_tuple) # 👇️ fruits: ('apple', 'banana', 'kiwi') print(result)

If you aren't sure what type a variable stores, use the built-in type() class.

my_str = 'fruits: ' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True my_tuple = ('apple', 'banana', 'kiwi') print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

If you declared a tuple by mistake, tuples are constructed in the following ways:

  • Using a pair of parenthesis () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor
Use the search field on my Home Page to filter through my more than 1,000 articles.