DEV Community

Cover image for How to fix "can only concatenate str (not “int”) to str" in Python
Reza Lavarian
Reza Lavarian

Posted on • Originally published at decodingweb.dev

How to fix "can only concatenate str (not “int”) to str" 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 “int”) to str” occurs if you try to concatenate a string with an integer (int object).

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

Traceback (most recent call last):
File "/dwd/sandbox/test.py", line 6, in 
output = 'User: ' + user['name'] + ', Score: ' + user['score']
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~
TypeError: can only concatenate str (not "int") 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 
  output = 'User: ' + user['name'] + ', Score: ' + user['score']
TypeError: cannot concatenate 'str' and 'int' objects
Enter fullscreen mode Exit fullscreen mode

But it occurs for the same reason: concatenating a string with an integer.

How to fix "TypeError: can only concatenate str (not "int") 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 with '4' because one is an integer (4) and the other is a string containing a numeric character ('4').

This TypeError might happen in two scenarios:

  1. Scenario #1: when concatenating a string with a numeric value
  2. Scenario #2: when adding two or more numbers

Let's explore the solutions.

⚠️ Scenario #1: when concatenating a string with a numeric value

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

# ⛔ Raises TypeError: can only concatenate str (not “int”) to str
user = {
    'name': 'John',
    'score': 75
}

output = 'User: ' + user['name'] + ', Score: ' + user['score']
print(output)
Enter fullscreen mode Exit fullscreen mode

In the above example, user['score'] contains a numeric value (75) and can't be directly concatenated to the string.

Python provides various methods for inserting integer values 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 integers. All you need to do is to convert the numbers into string values with the str() function:

user = {
    'name': 'John',
    'score': 75
}

print('User: ' + user['name'] +', Score: ' + str(user['score']))
# output: User: John, Score: 75
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.

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

user = {
    'name': 'John',
    'score': 75
}

print(f'User: {user["name"]}, Score: {user["score"]}')
# output: User: John, Score: 75
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.

user = {
    'name': 'John',
    'score': 75
}

print('User: %s, Score: %s' % (user['name'], user['score']))
# output: User: John, Score: 75
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 integers 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.

user = {
    'name': 'John',
    'score': 75
}

print('User:', user)
# output: User: {'name': 'John', 'score': 75}
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 numbers

This error doesn't only happen when you intend to concatenate strings. It can also occur when you try to add two or more numbers, but it turned out one of them was a string. For instance, you get a value from a third-party API or even the input() function:

devices = input('How many iphones do you want to order:  ')
unit_price = 900

# total cost with shipping (25)
total_cost = devices * unit_price + 25
Enter fullscreen mode Exit fullscreen mode

The above code is a super-simplified program that takes iPhone pre-orders. It prompts the user to input the number of devices they need and outputs the total cost - including shipping.

But if you run the code, it raises TypeError: can only concatenate str (not “int”) to str.

The reason is the input() reads an input line and converts it to a string. And once we try to add the input value (which is now a string) to 25, we get a TypeError.

The reason is Python's interpreter assumes we're trying to concatenate strings.

To fix the issue, you need to ensure all operands are numbers. And for those that aren't, you can cast them to an integer with the int() function:

devices = input('Number of iphones: ')
unit_price = 900

# total cost with shipping (25)
total_cost = int(devices) * unit_price + 25
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!

❤️ You might like:

Top comments (0)