Unsupported operand type s for str and str ошибка

a’$’

money=1000000;
portfolio=0;
value=0;
value=(yahoostock.get_price('RIL.BO'));
portfolio=(16*(value));
print id(portfolio);
print id(value);
money= (money-portfolio);
'''

I am getting the error:

Traceback (most recent call last):
  File "/home/dee/dee.py", line 12, in <module>
    money= (value-portfolio);
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Since money is integer and so is portfolio, I cant solve this problem..anyone can help???

Chriszuma's user avatar

Chriszuma

4,42422 silver badges19 bronze badges

asked Oct 4, 2011 at 20:03

user979204's user avatar

4

value=(yahoostock.get_price('RIL.BO'));

Apparently returns a string not a number. Convert it to a number:

value=int(yahoostock.get_price('RIL.BO'));

Also the signal-to-noise ratio isn’t very high. You’ve lots of (,), and ; you don’t need. You assign variable only to replace them on the next line. You can make your code nicer like so:

money = 1000000
value = int(yahoostock.get_price('RIL.BO'));
portfolio = 16 * value;
print id(portfolio);
print id(value);
money -= portfolio;

answered Oct 4, 2011 at 20:20

Winston Ewert's user avatar

Winston EwertWinston Ewert

44k10 gold badges68 silver badges83 bronze badges

money and portfolio are apparently strings, so cast them to ints:

money= int( float(money)-float(portfolio) )

answered Oct 4, 2011 at 20:04

Chriszuma's user avatar

ChriszumaChriszuma

4,42422 silver badges19 bronze badges

As the error message clearly states, both are string, cast with int(var).

Note:

Let’s see what can we decude from the error message:

portfolio must be string(str), which means value is also a string. Like this:

>>> 16*"a"
'aaaaaaaaaaaaaaaa'

and apparently you missed to post relevant code because the error message tells you that money is str as well.

answered Oct 4, 2011 at 20:10

Karoly Horvath's user avatar

Karoly HorvathKaroly Horvath

94.3k11 gold badges116 silver badges176 bronze badges

I think the problem here is assuming that because you have initialised variables with integer values they will remain as integers. Python doesn’t work this way. Assigning a value with = only binds the name to the value without paying any attention to type. For example:

a = 1       # a is an int
a = "Spam!" # a is now a str

I assume yahoostock.getprice(), like many functions that get data from websites, returns a string. You need to convert this using int() before doing your maths.

answered Oct 4, 2011 at 20:18

neil's user avatar

neilneil

3,3371 gold badge14 silver badges11 bronze badges

The python error TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’ occurs when you try to subtract a string from another that contains numbers in both strings. The TypeError is due to the operand type minus (‘-‘) is unsupported between str (string). Auto casting is not supported by python. You can subtract a number from a different number. If you try to subtract a string from another string that may contain a number, the error TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’ will be thrown.

In python, an arithmetic operation can be used between valid numbers. For example, you can subtract a number from a different number. The integer can be subtracted from a float number. If you try to subtract a string from a string that contains a number, the error TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’ will be thrown.

Objects other than numbers can not be used in python substraction. The arithmetic subtract can be used only for numbers. If a number is stored as a string, it should be converted to an integer before subtracting it from each string. If you try to subtract a string to a string containing a number, the error TypeError: unsupported operand type(s) for +: ‘str’ and ‘str’ will be shown.

Exception

The error TypeError: unsupported operand type(s) for-: ‘str’ and ‘str’  will be shown as below the stack trace. The stack trace shows the line where a string is subtracted from a string that may contain valid numbers.

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x - y
TypeError: unsupported operand type(s) for -: 'str' and 'str'
[Finished in 0.0s with exit code 1]

How to reproduce this error

If you try to subtract a string from another string containing a number, the error TypeError: unsupported operand type(s) for-: ‘str’ and ‘str’ will be reproduced. Create two python variables. Assign variables with a string that contains a valid number. Subtract from the string to another string.

x = '5'
y = '2'
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 -: 'str' and 'str'
[Finished in 0.0s with exit code 1]

Root Cause

Python does not support auto casting. The arithmetic operation subtraction can be used to subtract between two valid numbers. If a string is subtracted from another string, this error will be thrown. The string may contain a valid number. The string should be converted to integer before subtracting.

Solution 1

If you try to subtract a string from another string contains a valid number, convert the string to an integer using the built in function int(). This will resolve the error. The built in function int() converts a string contains a valid number to an integer number.

x = int('5')
y = int('2')
print x - y

Output

3
[Finished in 0.1s]

Solution 2

If you are trying to subtract a string from a string containing a valid number, change the string to an integer. This is going to address the error TypeError: unsupported operand type(s) for-: ‘str’ and ‘str’ . You can not subtract a string from another string.

x = 5
y = 2
print x - y

Output

3
[Finished in 0.1s]

Solution 3

If the variable type is unknown, the variable type should be checked before subtracting the number to another number. The example below shows the method of verification before subtracting the numbers

x = '5'
y = '2'
if (x is int) and (y is int) :
	print x - y
else :
	print "Not a number"

Output

Not a number
[Finished in 0.0s]

А вот и полный код

what = input( "Что делаем? (+,-):" )


a = input("Введи первое число: ")
b = input("Введи второе число: ")

if what == "+":
	c = a + b
	print("Результат: " + c)
elif what == "-":
	c = a - b
	print("Результат: " + c)
else:
 	print("Выбрана неверная операция!")


  • Вопрос задан

    21 мар.

  • 257 просмотров

Пригласить эксперта

Функция input по стандарту возвращает строку (объект типа str). Невозможно вычесть строку из строки (для двух объектов типа strне определен метод __sub__). Нужно явно привести a и b к целым числам (int) или числам с плавающей точкой (float). Объекты этого типа можно вычитать друг из друга.

a = int(input())
b = int(input())

a = int(input("Введи первое число: "))
b = int(input("Введи второе число: "))


  • Показать ещё
    Загружается…

09 июн. 2023, в 01:21

10000 руб./за проект

09 июн. 2023, в 01:06

50000 руб./за проект

09 июн. 2023, в 00:36

1000 руб./за проект

Минуточку внимания

One error that you might get in Python is:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

This error occurs when you try to subtract a string value from another string.

The following tutorial shows an example that causes this error and how to fix it.

How to reproduce this error

This error occurs when you put two strings as operands to the subtraction - operator as shown below:

x = "a" - "b"

# TypeError: unsupported operand type(s) for -: 'str' and 'str'

The most common cause for this error is when you use the input() function to ask for two numbers in Python.

Suppose you want to ask users for two numbers, then reduce the first with the second as follows:

x = input("Input the first number: ")
y = input("Input the second number: ")

z = x - y

Output:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    z = x - y
TypeError: unsupported operand type(s) for -: 'str' and 'str'

The input() function returns the user input as a string type. When you subtract the number y from x to produce z, the error will be raised.

How to fix this error

To resolve this error, you need to convert both strings into numbers.

This can be done using the int or float function, depending on whether you’re processing integers or floats.

The following is an example of processing integers:

x = input("Input the first number: ")
y = input("Input the second number: ")

z = int(x) - int(y)

Or if you have floats:

x = input("Input the first number: ")
y = input("Input the second number: ")

z = float(x) - float(y)

Both integers and floats are supported by the subtraction - operator, so you won’t raise this error.

I hope this tutorial is helpful. Happy coding! 👍

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!

Понравилась статья? Поделить с друзьями:
  • Unsupported operand type s for int and str ошибка
  • Unsupported operand type s for int and list ошибка
  • Unsupported operand type s for float and float ошибка
  • Unsupported compression method unarc dll вернул код ошибки
  • Unsupported command 7 zip ошибка