Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to generate a program that controls all the characters of a string and if any of them are not natural digits then the program will display False otherwise it will return True.

This is what i have so far:

numbers = ["0123456789"]

if len(str) > 0:

    for i in str:

        if i not in numbers:

            return False

        else:

            return True

I am not getting the desired output...

1 Answer

0 votes
by (108k points)
edited by

Firstly, you need to eliminate the numbers from the list as you are associating each character to all the digits at once i.e "1" == "0123456789", you also need to verify every char before returning True:

def is_dig(s):

    numbers = "0123456789"  # single iterable of the numbers

    for i in s:

        if i not in numbers:

            return False

    return bool(s) # return outside the loop also catching the empty string

A more effective way would be to use the ord() function and all() function:

def is_dig(s):

    return len(s) > 0 and all(48 <= ord(ch) <= 57 for ch in s)

#The ord of "0" is 48 and the ord of "9" is 57 so if the ord of the char falls in that range then you have a digit, if not all will short circuit and return False.

If you use the ord function without the all() then you will get something like this:

def is_dig(s):

    if not s: # empty string

        return False

    for ch in s:

        if not 48 <= ord(ch) <= 57:

            return False

    return True

If you want to learn python then do check out the below python tutorial video for better understanding:

Browse Categories

...