How to fix “TypeError: can only concatenate str (not “list”) to str” in Python

Updated Sep 22, 2023 ⤳ 5 min read

The Python error “TypeError: can only concatenate str (not “list”) to str” occurs if you concatenate a string with a list. 

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.

🎧 Debugging Jam

Calling all coders in need of a rhythm boost! Tune in to our 24/7 Lofi Coding Radio on YouTube, and let's code to the beat – subscribe for the ultimate coding groove!" Let the bug-hunting begin! 🎵💻🚀

How to fix it?

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:

  1. Convert the list into a string value with the str.join() method
  2. Access list items individually
  3. Use print() with multiple arguments - ideal for debugging
  4. Use an f-string
  5. Use printf-style formatting

Let's explore each method.

1. 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!

2. 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

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.

4. 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

5. 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!

Disclaimer: This post may contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.

`
Exit mobile version