Typeerror unsupported operand type s for int and str как исправить

This type of error would be caused by something along these lines:

"some string" + anInt - anotherInt

The problem arises because of the String in this statement- the compiler interprets the plus sign as combining the String and int together. However, in this context, it doesn’t know what to do with a minus sign- you can’t subtract an int from a string.

Your problem can be solved by putting your integer operations inside sets of parenthesis- i.e.,

"some string" + (anInt - anotherInt)

If you’re still having trouble, we can review your exact code and see where these parenthesis should be added- but this may be enough to get by on your own, which is always preferable!


EDIT: I’ll leave the above post in case it is part of the issue as well, but after reviewing the code again, you have this line of code:

A = ( (14 - 'month') /12)

In which you’re subtracting the String ‘month’ from the int 14. That’d probably be a problem.

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
  • 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
Table of Python Arithmetic Operators

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]

Ситуация: начинающий программист более-менее освоил JavaScript и перешёл к Python. Чтобы освоить новый язык на практике, программист решил переписать свой старый проект с JavaScript на Python и столкнулся с таким фрагментом:

var a = 2;
var b = ' ствола';
var c = a + b;

Программист помнит, что в Python для переменных не нужен var, а можно просто объявлять их в нужном месте, поэтому он написал такой код:

a = 2
b = ‘ ствола’
c = a + b

Но при запуске проекта компьютер указал на последнюю строку и выдал ошибку:

Exception has occurred: TypeError
unsupported operand type(s) for +: ‘int’ and ‘str’

Почему так происходит: в JavaScript есть автоматическое приведение типов, и компьютер берёт на себя перевод данных из одного типа в другой. В нашем примере он сделает так:

  1. Возьмёт число и строку.
  2. Увидит, что их нужно сложить.
  3. Посмотрит по своим правилам, к какому одному типу проще всего привести всё в этой ситуации. 
  4. Поймёт, что проще перевести число в строку, чем наоборот.
  5. Сделает так и на выходе получит строку «2 ствола»

Но Python так не умеет — ему нужно, чтобы данные были одного типа или хотя бы из одного семейства: оба числовые, оба строковые и так далее. Так как сейчас идёт сложение разных типов данных, то Питон говорит, что он так делать не будет, и падает с ошибкой.

Что делать с ошибкой Exception has occurred: TypeError

Чтобы исправить эту ошибку, нужно вручную привести данные к одному типу или явно указать их при операции.

В нашем случае можно сделать так: при сложении сказать компьютеру напрямую, что мы хотим в сложении использовать переменную a как строку:

a = 2
b = ‘ ствола’
c = str(a) + b

Команда str() не меняет тип и содержимое переменной a, но зато компьютер понимает, что это временно стало строкой, и спокойно её складывает со второй строкой.

Понравилась статья? Поделить с друзьями:
  • Как найти мощность рассеивания на резисторе
  • Как найди телефона нокиа
  • Как найти страницы ссылающиеся на сайт
  • Как найти хорошую музыку которая нравится
  • Как найти напряжение цинка