TypeError: can only concatenate str (not “float”) to str (solutions)
TypeError: can only concatenate str (not “float”) to str” occurs if you try to concatenate a string with a floating point number (float
).
🎧 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! 🎵💻🚀
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
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
But it occurs for the same reason: concatenating a string with a floating point number.
Psssst! Do you want to learn web development in 2023?
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:
- Scenario #1: when concatenating a string with a floating point number
- 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'])
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:
- The str() function
- Formatted string literals (a.k.a f-strings)
- Printf-style formatting
- Using print() with multiple arguments (ideal for debugging)
1. 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
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.
2. 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
Please note that f-string was added to Python from version 3.6. For older versions, check out the str.format() function.
3. 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
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.
4. 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
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 the input()
function. Assuming it's a number, you use it in an expression like so:
# ⛔ raises TypeError: can only concatenate str (not float) to str
price = '49.42'
shipping_cost = 7.25
total_cost = price + shipping_cost
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
It should solve the problem.
Alright, I think that does it! I hope this quick guide helped you fix your problem.
Thanks for reading!
Never miss a guide like this!
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.