TypeError: unsupported operand type(s) for /: str and float

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: unsupported operand type(s) for /: str and float #

The Python "TypeError: unsupported operand type(s) for /: 'str' and 'float'" occurs when we try to use the division / operator with a string and a floating-point number. To solve the error, convert the string to a float, e.g. float(my_str) / my_float.

typeerror unsupported operand type for slash str and float

Here is an example of how the error occurs.

main.py
my_str = '8.8' my_float = 4.2 # ⛔️ TypeError: unsupported operand type(s) for /: 'str' and 'float' result = my_str / my_float

We are trying to use the division operator with a string and a float.

To solve the error, we have to convert the string to a number (a float or an int).

main.py
my_str = '8.8' my_float = 4.2 result = float(my_str) / my_float print(result) # 👉️ 2.0952380952380953

We used the float() class to convert the string to a floating-point number before using the division operator.

IMPORTANT: if you use the input() built-in function, all of the values the user enters get converted to strings (even numeric values).

If you have a string that may also contain characters but you need to extract a float value, use the re.findall() method.

main.py
import re my_str_1 = 'ab8.8cd' m = re.findall(r'\d+\.\d+', my_str_1) print(m) # 👉️ ['8.8'] my_float_2 = 4.2 if len(m) > 0: result = float(m[0]) / my_float_2 print(result) # 👉️ 2.0952380952380953

The re.findall method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
my_str_1 = '8.8' print(type(my_str_1)) # 👉️ <class 'str'> print(isinstance(my_str_1, str)) # 👉️ True my_float = 4.2 print(type(my_float)) # 👉️ <class 'float'> print(isinstance(my_float, float)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Conclusion #

The Python "TypeError: unsupported operand type(s) for /: 'str' and 'float'" occurs when we try to use the division / operator with a string and a floating-point number. To solve the error, convert the string to a float, e.g. float(my_str) / my_float.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.