Error unsupported operand types

Одна ошибка, с которой вы можете столкнуться при использовании 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'], 'poi

Как исправить: 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]

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

Strings can be concatenated in Python. This lets you merge the value of two or more strings into one string. If you try to concatenate a string and a value equal to None, you’ll encounter the “TypeError: unsupported operand type(s) for +: ‘nonetype’ and ‘str’” error.

This guide talks about what this error means and why it is raised. It discusses an example of this error so you can figure out how to fix it in your code.

Get offers and scholarships from top coding schools illustration

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

Email

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 +: ‘nonetype’ and ‘str’

The concatenation operator (+) merges string values:

day = "Monday"
weather = "sunny"
print("It's " + day + " and it is " weather + " outside.")

This code merges the “It’s”, “Monday”, “and it is ”, “sunny”, and “outside.” strings into one long string. The code returns: “It’s Monday and it is sunny outside.”.

The concatenation operator cannot be used to merge values of different data types, such as a string and an integer. This is because the plus sign has different associations with data types like an integer. With integers and floats, the plus sign represents the addition operation.

Values equal to None cannot be concatenated with a string value. This causes the error “TypeError: unsupported operand type(s) for +: ‘nonetype’ and ‘str’”.

An Example Scenario

Let’s build a program that prints out a message displaying information about how much a shoe shop has earned in the last month. This information includes the net and gross income of the store, the value of the highest sale, and the value of the average sale, at the shoe store. 

To start, declare a dictionary that stores some values about what the shoe shop has earned in a month:

turnover = {
	   "month": "July",
	   "net_income": 7203.97,
	   "gross_income": 23821.30,
	   "highest_sale": 320.00,
	   "average_sale": 45.00
}

The owner of the shoe store wants to see these values when they run the program. You’re going to use a print statement to access the values about turnover at the store. Use five print statements to display the information in the dictionary:

print("Month: ") + turnover["month"]  
print("Net income: $") + str(turnover["net_income"])
print("Gross income: $") + str(turnover["gross_income"])
print("Highest sale: $") + str(turnover["highest_sale"])
print("Average sale: $") + str(turnover["average_sale"])

We convert all of the floating-point values in the dictionary to a string. This prevents an error that occurs when you try to concatenate a string and a float. As discussed earlier, only strings can be concatenated to strings. Next, run the code and see what happens:

Month
Traceback (most recent call last):
  File "main.py", line 9, in <module>
	     print("Month") + turnover["month"]  
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

The code returns an error.

The Solution

The code successfully prints out the word “Month” to the console. The program stops working when you try to add the value of turnover[“month”] to the “Month” string.

The issue is that you’re concatenating the turnover[“month”] string outside of the print() statement. The print() function returns None. Because your concatenation operator comes after the print() statement, Python thinks that you are trying to add a value to it:

print("Month") + turnover["month"]  

To solve this error, we must move the concatenation operation into the print() statements:

print("Month: " + turnover["month"])
print("Net income: $" + str(turnover["net_income"]))
print("Gross income: $" + str(turnover["gross_income"]))
print("Highest sale: $" + str(turnover["highest_sale"]))
print("Average sale: $" + str(turnover["average_sale"]))

Concatenation operators should always come after a string value, not the print() statement whose value you want to concatenate. Let’s execute the program:

Month: July
Net income: $7203.97
Gross income: $23821.3
Highest sale: $320.0
Average sale: $45.0

Our code successfully executes all of the print() statements. Each print statement contains a label to which a value from the “turnover” dictionary is concatenated.

Conclusion

The “TypeError: unsupported operand type(s) for +: ‘nonetype’ and ‘str’” error is raised when you try to concatenate a value equal to None with a string. This is common if you try to concatenate strings outside of a print() statement.

To solve this error, check the values on both sides of a plus sign are strings if you want to perform a concatenation operation.

Now you’re ready to fix this error in your Python program like a professional coder!

Понравилась статья? Поделить с друзьями:
  • Error unsupported dictionary type mysql
  • Error unsupported cpu installed что это
  • Error unsupported cpu installed pc will automatically power down in a few seconds
  • Error unsupported compression method xprecomp
  • Error unsupported compression method pzlib