The Python error “TypeError: can only concatenate str (not “list”) to str” occurs if you concatenate a string with a list.
✋ Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza
Here’s what the error looks like on Python 3.
File "/dwd/sandbox/test.py", line 3, in
print('Resources: ' + books)
~~~~~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "list") to str
On Python 2.7, the error is slightly different, though:
Traceback (most recent call last):
File "test.py", line 3, in
print('Resources: ' + books)
TypeError: cannot concatenate 'str' and 'list' objects
But it occurs for the same reason.
Why does it happen?
As you probably know, programming languages are either strongly typed or loosely typed.
Strongly-typed programming languages such as Python have a strict type system to help the programmer avoid data-type-related mistakes - meaning some operations aren't allowed on some data types. For instance, you can't divide 20
by '4'
(because '4'
is a string value) - depending on the operation, the error messages might vary.
Whenever you declare a variable like name = 'John'
, as a dynamically-typed language, Python determines the data type to be a string.
Now, if you try to concatenate it with a list, you'll get the "TypeError: can only concatenate str (not "list") to str" error.
How to fix TypeError: can only concatenate str (not "list") to str
Fixing type errors such as this one is easy. If you need to use the + operator, check if the operands on either side have the same type. Remember: birds of a feather flock together 🦜 +
🦜
But if you want to insert the values into a string, there are multiple ways of doing it:
Convert the list into a string value with the str.join() method
Access list items individually
Use print() with multiple arguments - ideal for debugging
Use an f-string
Use printf-style formatting
Let's explore each method.
Convert the list into a string with the str.join()
method: If you want to concatenate the items of a list to a string value, use str.join()
like so:
books = ['Fluent Python', 'Head First Python']
output = 'Resources: ' + ', '.join(books)
print(output)
# output: Resources: Fluent Python, Head First Python
In the above code, we separate the list items by a comma. Please note we call the join method on the separator string (in this case: ', '
). It seems weird, but that's how it works!
Access list items individually: Sometimes, you need to concatenate a single list item with a string value, but you use the whole list object by mistake.
In that case, you need to access the item by its index:
books = ['Fluent Python', 'Head First Python']
output = 'Top Pick: ' + books[1]
print(output)
# output: Top Pick: Head First Python
Use print()
with multiple arguments - ideal for debugging: If you're concatenating a string with a list and readability isn't a concern, you can pass the string and the list as separate arguments to the print()
function.
All the positional arguments passed to the print()
function are automatically converted to strings - like how str()
works.
books = ['Fluent Python', 'Head First Python']
print('Fetched these books:', books)
# output: Fetched these books: ['Fluent Python', 'Head First Python']
As you can see, the print()
function outputs the arguments separated by a space. You can also change the separator via the sep keyword argument.
Use an f-string: Formatted string literals (a.k.a f-strings) are a robust way of formatting strings because they allow you to use Python expressions directly in string values (in a pair of curly brackets {}
).
You create an f-string by prefixing it with f
or F
and writing expressions inside curly braces:
books = ['Fluent Python', 'Head First Python']
print(f'Fetched these books: {books}')
# output: Fetched these books: ['Fluent Python', 'Head First Python']
Additionally, you can join the list items before using it in the string:
books = ['Fluent Python', 'Head First Python']
book_list = ', '.join(books)
print(f'Fetched these books: {book_list}')
# output: Fetched these books: Fluent Python, Head First Python
Use printf-style formatting: In the old string formatting (a.k.a printf-style string formatting), we use the %
(modulo) operator to generate dynamic strings (string %
values).
The string operand is a string literal containing one or more placeholders identified with %
, while the values operand can be a single value or a tuple of values.
books = ['Fluent Python', 'Head First Python']
print('Fetched these books: %s' % books)
# output: Fetched these books: ['Fluent Python', 'Head First Python']
When using the old-style formatting, check if your format string is valid. Otherwise, you'll get another type error: not all arguments converted during string formatting.
Alright, I think that does it! I hope this quick guide helped you fix your problem.
Thanks for reading!
❤️ You might like:
Not all arguments converted during string formatting error in Python (Fixed)
TabError: inconsistent use of tabs and spaces in indentation (Python)
How to fix the "TypeError: unhashable type: 'dict'" error in Python
TypeError: missing 1 required positional argument: 'self' (Fixed)
Unindent does not match any outer indentation level error in Python (Fixed)