Python provides support for arithmetic operations between numerical values with arithmetic operators. Suppose we try to perform certain operations between a string and an integer value, for example, concatenation +. In that case, we will raise the error: “TypeError: unsupported operand type(s) for +: ‘str’ and ‘int’”.
This tutorial will go through the error with example scenarios to learn how to solve it.
Table of contents
- TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
- What is a TypeError?
- Artithmetic Operators
- Example: Using input() Without Converting to Integer Using int()
- Solution
- Variations of TypeError: unsupported operand type(s) for: ‘int’ and ‘str’
- TypeError: unsupported operand type(s) for -: ‘int’ and ‘str’
- Solution
- TypeError: unsupported operand type(s) for /: ‘int’ and ‘str’
- Solution
- TypeError: unsupported operand type(s) for %: ‘int’ and ‘str’
- Solution
- TypeError: unsupported operand type(s) for ** or pow(): ‘int’ and ‘str’
- Solution
- TypeError: unsupported operand type(s) for //: ‘int’ and ‘str’
- Solution
- TypeError: unsupported operand type(s) for -: ‘int’ and ‘str’
- Summary
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
What is a TypeError?
TypeError tells us that we are trying to perform an illegal operation for a specific Python data type. TypeError exceptions may occur while performing operations between two incompatible data types. In this article, the incompatible data types are string and integer.
Artithmetic Operators
We can use arithmetic operators for mathematical operations. There are seven arithmetic operators in Python:
| Operator | Symbol | Syntax |
|---|---|---|
| Addition | + | x + y |
| Subtraction | – | x -y |
| Multiplication | * | x *y |
| Division | / | x / y |
| Modulus | % | x % y |
| Exponentiation | ** | x ** y |
| Floor division | // | x // y |
All of the operators are suitable for integer operands. We can use the multiplication operator with string and integer combined. For example, we can duplicate a string by multiplying a string by an integer. Let’s look at an example of multiplying a word by four.
string = "research" integer = 4 print(string * integer)
researchresearchresearchresearch
Python supports multiplication between a string and an integer. However, if you try to multiply a string by a float you will raise the error: TypeError: can’t multiply sequence by non-int of type ‘float’.
However, suppose we try to use other operators between a string and an integer. Operand x is a string, and operand y is an integer. In that case, we will raise the error: TypeError: unsupported operand type(s) for: [operator]: ‘str’ and ‘int’, where [operator] is the arithmetic operator used to raise the error. If operand x is an integer and operand y is a string, we will raise the error: TypeError: unsupported operand type(s) for: [operator]: ‘int’ and ‘str’. Let’s look at an example scenario.
Example: Using input() Without Converting to Integer Using int()
Python developers encounter a common scenario when the code takes an integer value using the input() function but forget to convert it to integer datatype. Let’s write a program that calculates how many apples are in stock after a farmer drops off some at a market. The program defines the current number of apples; then, the user inputs the number of apples to drop off. We will then sum up the current number with the farmer’s apples to get the total apples and print the result to the console. Let’s look at the code:
num_apples = 100
farmer_apples = input("How many apples are you dropping off today?: ")
total_apples = num_apples + farmer_apples
print(f'total number of apples: {total_apples}')
Let’s run the code to see what happens:
How many apples are you dropping off today?: 50 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) 1 total_apples = num_apples + farmer_apples TypeError: unsupported operand type(s) for +: 'int' and 'str'
We raise the because Python does not support the addition operator between string and integer data types.
Solution
The solve this problem, we need to convert the value assigned to the farmer_apples variable to an integer. We can do this using the Python int() function. Let’s look at the revised code:
num_apples = 100
farmer_apples = int(input("How many apples are you dropping off today?: "))
total_apples = num_apples + farmer_apples
print(f'total number of apples: {total_apples}')
Let’s run the code to get the correct result:
How many apples are you dropping off today?: 50 total number of apples: 150
Variations of TypeError: unsupported operand type(s) for: ‘int’ and ‘str’
If we are trying to perform mathematical operations between operands and one of the operands is a string, we need to convert the string to an integer. This solution is necessary for the operators: addition, subtraction, division, modulo, exponentiation and floor division, but not multiplication. Let’s look at the variations of the TypeError for the different operators.
TypeError: unsupported operand type(s) for -: ‘int’ and ‘str’
The subtraction operator – subtracts two operands, x and y. Let’s look at an example with an integer and a string:
x = 100
y = "10"
print(f'x - y = {x - y}')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 print(f'x - y = {x - y}')
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Solution
We must convert the y variable to an integer using the int() function to solve this. Let’s look at the revised code and result:
x = 100
y = "10"
print(f'x - y = {x - int(y)}')
x - y = 90
TypeError: unsupported operand type(s) for /: ‘int’ and ‘str’
The division operator divides the first operand by the second and returns the value as a float. Let’s look at an example with an integer and a string :
x = 100
y = "10"
print(f'x / y = {x / y}')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 print(f'x / y = {x / y}')
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Solution
We must convert the y variable to an integer using the int() function to solve this. Let’s look at the revised code and result:
x = 100
y = "10"
print(f'x / y = {x / int(y)}')
x / y = 10.0
TypeError: unsupported operand type(s) for %: ‘int’ and ‘str’
The modulus operator returns the remainder when we divide the first operand by the second. If the modulus is zero, then the second operand is a factor of the first operand. Let’s look at an example with an and a string.
x = 100
y = "10"
print(f'x % y = {x % y}')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 print(f'x % y = {x % y}')
TypeError: unsupported operand type(s) for %: 'int' and 'str'
Solution
We must convert the y variable to an integer using the int() function to solve this. Let’s look at the revised code and result:
x = 100
y = "10"
print(f'x % y = {x % int(y)}')
x % y = 0
TypeError: unsupported operand type(s) for ** or pow(): ‘int’ and ‘str’
The exponentiation operator raises the first operand to the power of the second operand. We can use this operator to calculate a number’s square root and to square a number. Let’s look at an example with an integer and a string:
x = 100
y = "10"
print(f'x ** y = {x ** y}')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 print(f'x ** y = {x ** y}')
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'
Solution
We must convert the y variable to an integer using the int() function to solve this. Let’s look at the revised code and result:
x = 100
y = "10"
print(f'x ** y = {x ** int(y)}')
x ** y = 100000000000000000000
TypeError: unsupported operand type(s) for //: ‘int’ and ‘str’
The floor division operator divides the first operand by the second and rounds down the result to the nearest integer. Let’s look at an example with an integer and a string:
x = 100
y = "10"
print(f'x // y = {x // y}')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 print(f'x // y = {x // y}')
TypeError: unsupported operand type(s) for //: 'int' and 'str'
Solution
We must convert the y variable to an integer using the int() function to solve this. Let’s look at the revised code and result:
x = 100
y = "10"
print(f'x // y = {x // int(y)}')
x // y = 10
Summary
Congratulations on reading to the end of this tutorial! The error: TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ occurs when we try to perform addition between an integer value and a string value. Python does not support arithmetic operations between strings and integers, excluding multiplication. To solve this error, ensure you use only integers for mathematical operations by converting string variables with the int() function. If you want to concatenate an integer to a string separate from mathematical operations, you can convert the integer to a string. There are other ways to concatenate an integer to a string, which you can learn in the article: “Python TypeError: can only concatenate str (not “int”) to str Solution“. Now you are ready to use the arithmetic operators in Python like a pro!
Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.
Have fun and happy researching!
Как исправить: TypeError: неподдерживаемые типы операндов для -: 'str' и 'int'
17 авг. 2022 г.
читать 1 мин
Одна ошибка, с которой вы можете столкнуться при использовании Python:
TypeError : unsupported operand type(s) for -: 'str' and 'int'
Эта ошибка возникает при попытке выполнить вычитание со строковой переменной и числовой переменной.
В следующем примере показано, как устранить эту ошибку на практике.
Как воспроизвести ошибку
Предположим, у нас есть следующие Pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
'points_for': ['18', '22', '19', '14', '14', '11', '20', '28'],
'points_against': [5, 7, 17, 22, 12, 9, 9, 4]})
#view DataFrame
print(df)
team points_for points_against
0 A 18 5
1 B 22 7
2 C 19 17
3 D 14 22
4 E 14 12
5 F 11 9
6 G 20 9
7 H 28 4
#view data type of each column
print(df.dtypes )
team object
points_for object
points_against int64
dtype: object
Теперь предположим, что мы пытаемся вычесть столбец points_against из столбца points_for :
#attempt to perform subtraction
df['diff'] = df.points_for - df.points_against
TypeError : unsupported operand type(s) for -: 'str' and 'int'
Мы получаем TypeError , потому что столбец points_for является строкой, а столбец points_against — числовым.
Для выполнения вычитания оба столбца должны быть числовыми.
Как исправить ошибку
Чтобы устранить эту ошибку, мы можем использовать .astype(int) для преобразования столбца points_for в целое число перед выполнением вычитания:
#convert points_for column to integer
df['points_for'] = df['points_for'].astype (int)
#perform subtraction
df['diff'] = df.points_for - df.points_against
#view updated DataFrame
print(df)
team points_for points_against diff
0 A 18 5 13
1 B 22 7 15
2 C 19 17 2
3 D 14 22 -8
4 E 14 12 2
5 F 11 9 2
6 G 20 9 11
7 H 28 4 24
#view data type of each column
print(df.dtypes )
team object
points_for int32
points_against int64
diff int64
dtype: object
Обратите внимание, что мы не получаем ошибку, потому что оба столбца, которые мы использовали для вычитания, являются числовыми столбцами.
Дополнительные ресурсы
В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:
Как исправить KeyError в Pandas
Как исправить: ValueError: невозможно преобразовать число с плавающей запятой NaN в целое число
Как исправить: ValueError: операнды не могли транслироваться вместе с фигурами
The TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ error occurs when an integer value is added with a string that could contain a valid integer value. Python does not support auto casting. You can add an integer number with a different number. You can’t add an integer with a string in Python. The Error TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ will be thrown if an integer value is added to the python string.
In python, the plus “+” is used to add two numbers as well as two strings. The arithmetic addition of the two numbers is for numbers. For strings, two strings are concatenated. There is a need to concatenate a number and a string in programming. The plus “+” operator can not be used for this reason. When you concatenate an integer and a string, this error TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ is thrown.
The objects other than numbers can not use for arithmetic operation such as addition, subtraction etc. If you try to add a number to a string containing a number, the error TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ will be shown. The string should be converted to an integer before it is added to another number.
Exception
Through this article, we can see what this error TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ is, how this error can be solved. This type error is a mismatch of the concatenation of two different data type variables. The error would be thrown as like below.
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 3, in <module>
print x + y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
[Finished in 0.1s with exit code 1]
How to reproduce this issue
Create two separate data type variables in python, say an integer value and a string value. Using the plus “+” operator to concatenate these values. This error TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ will be seen due to the mismatch between the data types of the values.
The code below indicates the concatenation of two separate data type values. The value of x is the integer of y. The value of y is a string.
x = 5
y = "Yawin Tutor"
print x + y
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 3, in <module>
print x + y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
[Finished in 0.1s with exit code 1]
Different Variation of the error
TypeError: unsupported operand type(s) for +: 'int' and 'str'
TypeError: unsupported operand type(s) for -: 'int' and 'str'
TypeError: unsupported operand type(s) for /: 'int' and 'str'
TypeError: unsupported operand type(s) for %: 'int' and 'str'
TypeError: unsupported operand type(s) for //: 'int' and 'str'
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
TypeError: unsupported operand type(s) for -=: 'int' and 'str'
TypeError: unsupported operand type(s) for /=: 'int' and 'str'
TypeError: unsupported operand type(s) for %=: 'int' and 'str'
TypeError: unsupported operand type(s) for //=: 'int' and 'str'
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'
TypeError: unsupported operand type(s) for &=: 'int' and 'str'
TypeError: unsupported operand type(s) for |=: 'int' and 'str'
TypeError: unsupported operand type(s) for ^=: 'int' and 'str'
TypeError: unsupported operand type(s) for <<=: 'int' and 'str'
TypeError: unsupported operand type(s) for >>=: 'int' and 'str'
Root Cause
The error is due to the mismatch of the data type. Operators in python support the operation of the same data type. When an operator is used for two different data types, this type mismatch error will be thrown.
In the program, if two separate data types, such as integer and string, are used with plus “+” operators, they should first be converted to the same data type, and then an additional operation should be carried out.
Solution 1
Python cannot add a number and a string. Either both the variable to be converted to a number or a string. If the variables are changed to a number, the mathematical addition operation will be done. The error “TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’” will be resolved.
x = 5
y = 8
print x + y
Output
13
[Finished in 0.1s]
Solution 2
In the above program, The variables are converted to a string. Python interpreter concatenate two variables. the variable value is joined together. The example below shows the result of addition of two strings.
x = '5'
y = '8'
print x + y
Output
58
[Finished in 0.1s]
Solution 3
The above program is trying to add a string and an integer. Since python does not allow a string and an integer to be added, both should be converted to the same data type. The python function str() is used to convert an int to a string. Use the str() function to convert the integer number to the program.
x = 5
y = "Yawin Tutor"
print str(x) + y
Output
5Yawin Tutor
[Finished in 0.1s]
Solution 4
If two variables are added to the print statement, the print statement allows more than one parameter to be passed. Set the string statement and the integer as two parameters in the print statement. The print statement internally converts all values to the string statement. The code below shows how to use your print statement.
x = 5
y = "Yawin Tutor"
print x , y
Output
5Yawin Tutor
[Finished in 0.1s]
Solution 5
The Python program allows you to create a string by dynamically passing arguments. Create a string with a place holder. In the run-time, python replaces the place holder with the actual value.
x = 5
y = "Yawin Tutor"
print "{}".format(x) + y
or
print "{} Yawin Tutor".format(x)
Output
5 Yawin Tutor
[Finished in 0.1s]
Integer values cannot be subtracted from string values and vice versa. This is because strings and integers are separate data types. If you try to subtract a string from an integer, you receive an error like “TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’”.
In this guide, we talk about the significance of this error and why it is raised. We walk through an example to help you figure out how to solve this error in your code.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’
Unlike other programming languages, Python syntax is strongly typed. One consequence of this is you have to change the types of objects, like strings and integers, if you want to treat them as a different type of data.
When you try to subtract a string for an integer or vice versa, Python does not know what to do. This is because you cannot subtract string values.
Similarly, you cannot add a string to an integer or divide a string by an integer. These operations all return an “unsupported operand type(s)” error.
An Example Scenario
We’re going to build a spending application that tracks how much money someone will have left on their budget after making a purchase. This application asks a user to insert the value of each purchase they make. This will be subtracted from the total amount a user has in their budget.
To start, ask a user to set a budget using the input() method:
budget = int(input("What is your budget for this month? "))
We have converted this value to an integer using the int() method. Next, we ask a user to provide some details about their purchase. We ask about what they purchased and how much their purchase cost:
purchase = input("What did you purchase? ")
price = input("How much was this purchase? ")
Next, we subtract the value of “price” from “budget”. This tells us how much a user has left in their budget.
We do this using the subtraction operator (-):
money_left = budget - price
print("You have ${} left in your budget.".format(money_left))
Run our code to see if our program works:
What is your budget for this month? 400 What did you purchase? Monitor stand How much was this purchase? 35 Traceback (most recent call last): File "main.py", line 5, in <module> money_left = budget - price TypeError: unsupported operand type(s) for -: 'int' and 'str'
We’ve told our program our budget is $400 for the month. We have just purchased a monitor stand that cost $35. Our program fails to calculate our new budget. Let’s fix this error.
The Solution
To solve this error, we convert the value of “price” to a string.
By default, input() returns a string. We changed the value of “budget” to be an integer earlier in our code. However, we did not change the value of “price”. This results in our code subtracting an integer from a string which is not possible.
Python cannot automatically convert a string to an integer because Python is statically typed.
We solve this error by replacing the “price” declaration with this code:
price = int(input("How much was this purchase? "))
We have surrounded the input() statement with int(). This makes the value stored in the “price” variable an integer. This converts the value a user inserts into our program to an integer. Run our code with this revised line of code:
What is your budget for this month? 400 What did you purchase? Monitor stand How much was this purchase? 35 You have $365 left in your budget.
Our code runs successfully. Our code subtracts 35 from 400. Our program then prints out how much money we have left in our budget to the console.
Similar Errors
There are a number of “unsupported operand type(s)” errors in Python.
These errors mean the same thing: you are trying to perform a mathematical operation on a string and a numerical value. Because strings do not support mathematical operations, you’ll encounter an error.
For instance, you see this error if you try to add a string and an integer:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Similarly, you see this error if you try to find the remainder of a string and an integer:
TypeError: unsupported operand type(s) for %: 'int' and 'str'
To solve this error in all cases, make sure you convert any string values to an integer before you use them in your code. You can do this using the int() method.
Conclusion
The “TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’” error is raised when you try to subtract a string from an integer.
You solve this error by converting all strings to integers using the int() method before performing a mathematical operation.
Now you’re ready to solve this common Python error like a professional developer!
One error you may encounter when using Python is:
TypeError: unsupported operand type(s) for -: 'str' and 'int'
This error occurs when you attempt to perform subtraction with a string variable and a numeric variable.
The following example shows how to address this error in practice.
How to Reproduce the Error
Suppose we have the following pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
'points_for': ['18', '22', '19', '14', '14', '11', '20', '28'],
'points_against': [5, 7, 17, 22, 12, 9, 9, 4]})
#view DataFrame
print(df)
team points_for points_against
0 A 18 5
1 B 22 7
2 C 19 17
3 D 14 22
4 E 14 12
5 F 11 9
6 G 20 9
7 H 28 4
#view data type of each column
print(df.dtypes)
team object
points_for object
points_against int64
dtype: object
Now suppose we attempt to subtract the points_against column from the points_for column:
#attempt to perform subtraction
df['diff'] = df.points_for - df.points_against
TypeError: unsupported operand type(s) for -: 'str' and 'int'
We receive a TypeError because the points_for column is a string while the points_against column is numeric.
In order to perform subtraction, both columns must be numeric.
How to Fix the Error
To resolve this error, we can use .astype(int) to convert the points_for column to an integer before performing the subtraction:
#convert points_for column to integer
df['points_for'] = df['points_for'].astype(int)
#perform subtraction
df['diff'] = df.points_for - df.points_against
#view updated DataFrame
print(df)
team points_for points_against diff
0 A 18 5 13
1 B 22 7 15
2 C 19 17 2
3 D 14 22 -8
4 E 14 12 2
5 F 11 9 2
6 G 20 9 11
7 H 28 4 24
#view data type of each column
print(df.dtypes)
team object
points_for int32
points_against int64
diff int64
dtype: object
Notice that we don’t receive an error because both columns we used for the subtraction are numeric columns.
Additional Resources
The following tutorials explain how to fix other common errors in Python:
How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes
Python supports arithmetic operators to perform arithmetic operations between two numerical values. But if we perform the subtraction
-
operation between a string and an integer value, we will encounter the
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Error.
In this Python Error guide, we will discuss this error and see how to solve it. We will also walk through a Python example that demonstrates this error, so you can get an idea about how to solve this error in Python programs.
So let’s get started with the Error statement.
The Error Statement
TypeError: unsupported operand type(s) for -: 'str' and 'int'
is divided into two parts
Exception Type
and
Error Message
.
-
Exception Type (
TypeError
):
TypeError raises in Python when we try to perform an invalid operation on aPython data type object
.
-
Error Message(
unsupported operand type(s) for -: 'str' and 'int'
):
This error message is telling us that we are performing the subtraction operation between an integer and string value using
-
Operator. And the subtraction operation is illegal between a string and an integer value.
Python Error
The main reason why we encounter
TypeError: unsupported operand type(s) for -: 'str' and 'int'
errors is when we try to subtract a string value and an integer value using the subtraction operator
-
.
Python does not support the subtraction operation between a string value and an integer value, and if we try to perform it in our Program, we get the TypeError because Python is not capable of computing a string value with an integer value.
Example
# string number
str_num = "34"
# integer number
int_num = 44
# perfrom substraction (error)
result = str_num -int_num
print(result)
Output
Traceback (most recent call last):
File "main.py", line 8, in <module>
result = str_num -int_num
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Common Scenario
The most common scenario when many new Python learners encounter this error is when they input an integer value using the input function and forget to convert it into a
int
datatype. By default, the
input()
function returns the entered data into the string format. And when we use that input data with an integer value and perform the subtraction operation on them, we encounter this error.
Example
# integer value
total_price = 40_000_000
# string value
downpayment = input("How much do you want to pay as a Down Payment: ")
loan = total_price - downpayment
print("Your Loan Amount is:", loan)
Output
How much do you want to pay as a Down Payment: 482739
Traceback (most recent call last):
File "main.py", line 7, in <module>
loan = total_price - downpayment
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Break the code
In the above example, when we are asking the user to enter the
downpayment
value using the
input()
function, there we are acting the
downpayment
value as a string. And at line 7, we are subtracting the
downpayment
(string value) from the
total_price
(integer value)
total_price - downpayment
to compute the
loan
.
As Python does not support subtraction operation between a string value and an integer value, that’s why we receive the
unsupported operand type(s) for -: 'int' and 'str'
Error at line 7.
Solution
The solution for the above problem is very simple. All we need to do is convert the entered downpayment value to an integer value using the Python
int()
function. The Python
int()
function can convert a numeric string value to an integer value.
Example Solution
# integer value
total_price = 40_000_000
# integer value
downpayment = int(input("How much do you want to pay as a Down Payment: "))
loan = total_price - downpayment
print("Your Loan Amount is:", loan)
Output
How much do you want to pay as a Down Payment: 20_300_200
Your Loan Amount is: 19699800
Note:
In Python we can use underscore
_
between numbers to write a integer value for better readibility, for example integer value
2_000
is equal to
2000,
there is not difference.
Wrapping Up!
The Python Error
unsupported operand type(s) for -: 'int' and 'str'
is a TypeError that occurs when we perform the subtraction operation between an integer value and a string value.
Python also does not support the addition operation between a string and an integer, so if you perform the addition operation between an integer and a string, you will get a similar error
unsupported operand type(s) for +: 'int' and 'str'
.
If you are still getting this error in your Python program, please share your code in the comment section, and we will try to help you in debugging.
People are also reading:
-
Python TypeError: ‘float’ object cannot be interpreted as an integer Solution
-
Python TypeError: ‘NoneType’ object is not callable Solution
-
Python Error: TypeError: ‘tuple’ object is not callable Solution
-
Python typeerror: ‘int’ object is not subscriptable Solution
-
Python SyntaxError: positional argument follows keyword argument Solution
-
Python AttributeError: ‘NoneType’ object has no attribute ‘append’Solution
-
Python indexerror: list index out of range Solution
-
Python TypeError: ‘float’ object is not subscriptable Solution
-
Python TypeError: ‘int’ object is not callable Solution
-
Python local variable referenced before assignment Solution
Whether you are a newbie or an experienced programmer, you will occasionally encounter the “TypeError: unsupported operand type(s) for -: str and int” error when working with Python. If you are struggling with it, then continue reading the guide below to understand them.
Causes of the “TypeError: unsupported operand type(s) for -: str and int” error
This error occurs when you try to perform mathematical operations (addition, subtraction, multiplication, division) between a number and a string. Take a look at the code below to understand it better.
balance = 1000
withdrawal = input("How much are you withdrawing today? ")
balance = balance - withdrawal
print(f"Your balance: {balance}")
Output:
How much are you withdrawing today? 34.5
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Two easy ways to fix this problem
Basically, you just don’t attempt to subtract between a string and an integer, and you can avoid this error.
Here are two straightforward ways to fix it:
Using int() function
Syntax:
int(value, base)
Parameters:
value: A number that isn’t an int or a string.base: The number format. Default: base = 10.
In the above example, the input() function returns the entered data in string format. We will get an error when we take that input data and do a subtraction between string and an int.
The problem will be solved by converting the return value of the input() to an int value using the int() function. Like this:
balance = 1000
withdrawal = int(input("How much are you withdrawing today? "))
balance = balance - withdrawal
print(f"Your balance: {balance}")
Output:
How much are you withdrawing today? 50
Your balance: 950
Using float() function
Syntax:
float(value)
Parameter:
value: A number or a string that you want to convert to a floating point number.
We can solve the problem by replacing float() for int() in the example above. But the value returned between int() and float() is a different numeric type. So, depending on each case, choose to use float or int properly.
balance = 1000
withdrawal = float(input("How much are you withdrawing today? "))
balance = balance - withdrawal
print(f"Your balance: {balance}")
Output:
How much are you withdrawing today? 50.0
Your balance: 950.0
Summary
The “TypeError: unsupported operand type(s) for -: str and int” error in Python is a problem that is very easy to fix. You just need to understand the data type of each variable in your entire program. Hope this article is helpful to you. Thanks for reading!
Maybe you are interested:
- UnicodeDecodeError: ‘ascii’ codec can’t decode byte
- TypeError: Object of type DataFrame is not JSON serializable in Python
- TypeError: ‘dict’ object is not callable in Python
- TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘str’
- TypeError: ‘str’ object cannot be interpreted as an integer

Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.
Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
class Note(): def __init__(self, note, found=False): self.note = note self.found = found self.pith = ["до", "ре", "ми", "фа", "соль", "ля", "си"] self.pithT = ["до-о", "ре-э", "ми-и", "фа-а", "со-оль", "ля-а", "си-и"] def __eq__(self, other): if self.note == other: return True return False def __lt__(self, other): if self.pith.index(self.note) < other: return True return False def __gt__(self, other): if self.pith.index(self.note) > other: return True return False def __le__(self, other): if self.pith.index(self.note) <= other: return True return False def __ge__(self, other): if self.pith.index(self.note) >= other: return True return False def __lshift__(self, other): if (self.pith.index(self.note) - other) * -1 >= len(self.pith): return self.pithT[ (self.pith.index(self.note) - other) * -1 % len(self.pith) * -1] if self.found else self.pith[(self.pith.index(self.note) - other) * -1 % len(self.pith) * -1] return self.pithT[self.pith.index(self.note) - other] if self.found else self.pith[ self.pith.index(self.note) - other] def __rshift__(self, other): if other + self.pith.index(self.note) >= len(self.pith): return self.pithT[ (other + self.pith.index(self.note)) % len(self.pith)] if self.found else self.pith[ (other + self.pith.index(self.note)) % len(self.pith)] return self.pithT[other + self.pith.index(self.note)] if self.found else self.pith[ other + self.pith.index(self.note)] def get_interval(self, other): if ((self.pith.index(self.note) == 0 and self.pith.index(other) == 6) or (self.pith.index( self.note) == 6 and self.pith.index(other) == 0)): return 'септима' elif self.pith.index(self.note) == self.pith.index(other): return 'прима' elif self.pith.index(self.note) > self.pith.index(other): if self.pith.index(self.note) - self.pith.index(other) == 1: return 'секунда' elif self.pith.index(self.note) - self.pith.index(other) == 2: return 'терция' elif self.pith.index(self.note) - self.pith.index(other) == 3: return 'кварта' elif self.pith.index(self.note) - self.pith.index(other) == 4: return 'квинта' elif self.pith.index(self.note) - self.pith.index(other) == 5: return 'секста' elif self.pith.index(self.note) < self.pith.index(other): if self.pith.index(other) - self.pith.index(self.note) == 1: return 'секунда' elif self.pith.index(other) - self.pith.index(self.note) == 2: return 'терция' elif self.pith.index(other) - self.pith.index(self.note) == 3: return 'кварта' elif self.pith.index(other) - self.pith.index(self.note) == 4: return 'квинта' elif self.pith.index(other) - self.pith.index(self.note) == 5: return 'секста' N = 7 PITCHES = ["до", "ре", "ми", "фа", "соль", "ля", "си"] LONG_PITCHES = ["до-о", "ре-э", "ми-и", "фа-а", "со-оль", "ля-а", "си-и"] INTERVALS = ["прима", "секунда", "терция", "кварта", "квинта", "секста", "септима"] do = Note("до", True) re = Note("ре", True) mi = Note("ми", True) fa = Note("фа", True) sol = Note("соль", True) la = Note("ля", True) si = Note("си", True) r1 = do >> 1 print(r1) m1 = r1 >> 1 print(m1) f1 = m1 >> 1 print(f1) print() sl1 = re >> 1 >> 2 print(sl1) print() d2 = si >> 1 m2 = d2 >> 2 print(m2) mm2 = m2 >> 7 print(mm2) r2 = mm2 >> 55 print(r2) print() nf = si << 3 print(nf) nr = nf << 2 print(nr) print() nl2 = re << 3 print(nl2) nsol = do << 73 print(nsol) nm2 = mi << 21 print(nm2) print() nr = si << 2 << 1 << 2 print(nr) nf = nr << 2 << 4 << 6 print(nf) |
