How to check if a specific digit is in an integer

前端 未结 5 1039
我在风中等你
我在风中等你 2020-12-11 21:58

I want to check if, for example, the digit \'2\' is in 4059304593. My aim is to then check if there are any of the digits 1-9 not in my integer. This is what I have tried:

5条回答
  •  旧时难觅i
    2020-12-11 22:22

    Since you just want to find out which digits aren't in your number:

    def not_in_number(n):
        return {*range(10)} - {*map(int, {*str(n)})}
    

    Usage:

    >>> not_in_number(4059304593)
    {1, 2, 6, 7, 8}
    

    This takes the set of digits ({*range(10)}) and substracts from it the set of digits of your number ({*map(int, {*str(n)})}), created by mapping the set of digit characters to integers. If you find the {*...} notation confusing, you can always use set(...) instead, which will also work for Python 2.7+:

    def not_in_number(n):
        return set(range(10)) - set(map(int, set(str(n))))
    

提交回复
热议问题