How to fix "can only concatenate str (not “int”) to str" in Python
Tags: python, programming
Published: 2023-02-03 16:37:13

> ✋ **Update:** This post was originally published on my blog [decodingweb.dev](https://www.decodingweb.dev), where you can read the [latest version](https://www.decodingweb.dev/python-typeerror-can-only-concatenate-str-not-int-to-str-fixed) 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
```

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
```

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](https://www.decodingweb.dev/how-to-learn-a-programming-language#type-systems) - 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:

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

output = 'User: ' + user['name'] + ', Score: ' + user['score']
print(output)
```

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. <u>The `str()` function</u>
2. <u>Formatted string literals (a.k.a f-strings)</u>
3. <u>Printf-style formatting</u>
4. <u>Using `print()` with multiple arguments (ideal for debugging)</u>

**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:

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

print('User: ' + user['name'] +', Score: ' + str(user['score']))
# output: User: John, Score: 75
```

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 (`{}`):

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

print(f'User: {user["name"]}, Score: {user["score"]}')
# output: User: John, Score: 75
```

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.

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

print('User: %s, Score: %s' % (user['name'], user['score']))
# output: User: John, Score: 75
```

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.

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

print('User:', user)
# output: User: {'name': 'John', 'score': 75}
```

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:

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

# total cost with shipping (25)
total_cost = devices * unit_price + 25
```

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:

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

# total cost with shipping (25)
total_cost = int(devices) * unit_price + 25
```

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:**

- [TypeError: can only concatenate str (not "bool") to str (Fixed)](https://www.decodingweb.dev/python-typeerror-can-only-concatenate-str-not-bool-to-str-fix)
- [TypeError: can only concatenate str (not "dict") to str (Fixed)](https://www.decodingweb.dev/python-typeerror-can-only-concatenate-str-not-dict-to-str-fix)
- [TypeError: can only concatenate str (not "list") to str (Fixed)](https://www.decodingweb.dev/python-typeerror-can-only-concatenate-str-not-list-to-str-fix)
- [Not all arguments converted during string formatting error in Python (Fixed)](https://www.decodingweb.dev/python-typeerror-not-all-arguments-converted-during-string-formatting-fix)