DEV Community

Cover image for About 'can only concatenate str (not “float”) to str' error in Python
Reza Lavarian
Reza Lavarian

Posted on • Originally published at decodingweb.dev

About 'can only concatenate str (not “float”) to str' error in Python

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

TypeError: can only concatenate str (not “float”) to str” occurs if you try to concatenate a string with a floating point number (float).

Here’s what the error looks like on Python 3.

Traceback (most recent call last):
  File "/dwd/sandbox/test.py", line 6, in 
    print('Product: ' + book['title'] + ', price: $' + book['price'])
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~
TypeError: can only concatenate str (not "float") to str
Enter fullscreen mode Exit fullscreen mode

Python 2.7 displays a slightly different error:

Traceback (most recent call last):
  File "test.py", line 6, in 
    print('Product: ' + book['title'] + ', price: $' + book['price'])
TypeError: cannot concatenate 'str' and 'float' objects
Enter fullscreen mode Exit fullscreen mode

But it occurs for the same reason: concatenating a string with a floating point number.

How to fix "TypeError: can only concatenate str (not "float") to str"

If you need to use the + operator, check if the operands on either side are compatible. Remember: birds of a feather flock together 🦜 + 🦜

Python - as a strongly-typed programming language - doesn't allow some operations on specific data types. For instance, it disallows adding 4.5 with '4.5' because one is a floating point number (4.5) and the other is a string containing a numeric character ('4.5').

This TypeError might happen in two scenarios:

  1. Scenario #1: when concatenating a string with a floating point number
  2. Scenario #2: when adding two or more floating point numbers

Let's explore the solutions.

⚠️ Scenario #1: when concatenating a string with a floating point number

Python syntax disallows the use of a string and a number with the addition (+) operator:

# ⛔ raises TypeError: can only concatenate str (not float) to str
book = {
    'title': 'Head First Python',
    'price': 49.42
}

print('Product: ' + book['title'] + ', price: $' + book['price'])
Enter fullscreen mode Exit fullscreen mode

In the above example, book['price'] contains a numeric value (49.42) and can't be directly concatenated with the string.

Python provides various methods for inserting floating point numbers into strings:

  1. The str() function
  2. Formatted string literals (a.k.a f-strings)
  3. Printf-style formatting
  4. Using print() with multiple arguments (ideal for debugging)

The str() function: This is the easiest (and probably the laziest) method of concatenating strings with floating point numbers. All you need to do is to convert the floating point number into a string value by the str() function:

book = {
    'title': 'Head First Python',
    'price': 49.42
}

print('Product: ' + book['title'] + ', price: $' + str(book['price']))
# output: Product: Head First Python, price: 9.42
Enter fullscreen mode Exit fullscreen mode

Although it's easy to use, it might make your code harder to read if you have multiple numbers to convert. This lead us to the second method.

Formatted string literals (a.k.a f-strings): f-strings provide a robust way of inserting floating point numbers into string literals. You create an f-string by prefixing it with f or F and writing expressions inside curly braces ({}):

book = {
    'title': 'Head First Python',
    'price': 49.42
}

print(f'Product: {book["title"]}, price: {book["price"]}')
# output: Product: Head First Python, price: 49.42
Enter fullscreen mode Exit fullscreen mode

Please note that f-string was added to Python from version 3.6. For older versions, check out the str.format() function.

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 like so:

book = {
    'title': 'Head First Python',
    'price': 49.42
}

print('Product: %s, price: %s' % (book['title'], book['price']))
# output: Product: Head First Python, price: 49.42
Enter fullscreen mode Exit fullscreen mode

When using the old-style formatting, check if your format string is valid. Otherwise, you'll get another TypeError: not all arguments converted during string formatting.

Using print() with multiple arguments (ideal for debugging): If you only want to debug your code, you can pass the strings and the floating point numbers 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.

book = {
    'title': 'Head First Python',
    'price': 49.42
}

print('Product:', book['title'], '| price', book['price'])
# output: Product: Head First Python | price 49.42
Enter fullscreen mode Exit fullscreen mode

As you can see, the print() function outputs the arguments separated by a space. You can change the separator via the sep keyword argument.

⚠️ Scenario #2: when adding two or more floating point numbers

This TypeError doesn't only happen when you intend to concatenate strings, though. It can also occur when you try to add two or more numbers, but it turns out one of them is a string. For instance, you fetch the price of a product from a third-party API or even via the input() function.

Assuming it's a number, you use it in an expression like this:

# ⛔ raises TypeError: can only concatenate str (not float) to str
price = '49.42'
shipping_cost = 7.25

total_cost = price + shipping_cost
Enter fullscreen mode Exit fullscreen mode

But since the lefthand-side operand (price) is a string, Python interprets it as a concatenation expression. And since there's also a number in the "concatenation", it raises the TypeError saying "can only concatenate str (not "float") to str".

To fix the issue, you need to ensure all operands are numbers. And for those that aren't, you can cast them to a number by using float() or int() functions accordingly:

price = '49.42'
shipping_cost = 7.25

total_cost = float(price) + shipping_cost

print(total_cost)
# output: 56.67
Enter fullscreen mode Exit fullscreen mode

It should solve the problem.

Alright, I think that does it! I hope this quick guide helped you fix your problem.

Thanks for reading!

Top comments (1)

Collapse
 
Sloan, the sloth mascot
Comment deleted