TypeError: 'in <string>' requires string as left operand, not int

avatar

Borislav Hadzhiev

Last updated: Jul 13, 2022

banner

Photo from Unsplash

TypeError: 'in <string>' requires string as left operand, not int #

The Python "TypeError: 'in <string>' requires string as left operand, not int" occurs when we use the in operator with an integer and a string. To solve the error, wrap the integer in quotes, e.g. '5' in my_str.

Here is an example of how the error occurs.

main.py
my_str = '13579' result = 13 in my_str # ⛔️ TypeError: 'in <string>' requires string as left operand, not int print(result)

We used the in operator to check if an integer is contained in a string which caused the error.

To solve the error, we have to wrap the integer in quotes to make it as string.

main.py
my_str = '13579' result = '13' in my_str print(result) # 👉️ True if '13' in my_str: # 👇️ this runs print('13 is contained in the string') else: print('13 is NOT contained in the string')
Wrapping the integer in quotes solves the error because when the value on the right-hand side is a string, the value on the left-hand side must also be a string.

If you have the int stored in a variable, use the str() class to convert it to a string before using the in operator.

main.py
my_str = '13579' my_int = 13 result = str(my_int) in my_str print(result) # 👉️ True if str(my_int) in my_str: # 👇️ this runs print('13 is contained in the string') else: print('13 is NOT contained in the string')

The str() class can be used to convert an object (such as an int) to a string.

Once the values on the left-hand and right-hand sides are of the same type, the error is resolved.

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

main.py
my_str = 'num is 13579' print('5' in my_str) # 👉️ True print('0' in my_str) # 👉️ False

If you need to check if a substring is NOT in a string, use the not in operator instead.

main.py
my_str = 'num is 13579' print('5' not in my_str) # 👉️ False print('0' not in my_str) # 👉️ True

x not in s returns the negation of x in s.

All built-in sequences and set types support the in and not in operators.

Note that empty strings are always considered to be a substring of any other string.

main.py
my_str = '13579' print('' in my_str) # 👉️ True
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.