Skip to content Skip to sidebar Skip to footer

Using "in" Operator Compare/convert A String To An Int

I need to find if an integer is found in a list of strings. context = ['4', '6', '78'] if category.id in context: The code above is not working because I compare int(category id)

Solution 1:

You could also consider using a list comprehension to convert context to a list of integers.

context_ints = [int(i) for i in context]
if category.id in context_ints:
    ... do stuff ...

If context is guaranteed to be a list of strings that can sensibly be converted to integers, this may be the safest route for you.

Solution 2:

You could always just update the id to a string, like this:

classcat():
    def__init__(self, id):
        self.id = id

category = cat(4)

context = ['4', '6', '78']

ifstr(category.id) in context:
    print('True')

#outputTrue

Post a Comment for "Using "in" Operator Compare/convert A String To An Int"