简体   繁体   中英

Using a boolean to check if the number inside the string is a natural

So i'm trying to make a function to check if the numbers inside a string is natural.

So my code is like this

def natural(x):
     while True:
          return x.isdigit() and 0 <= int(x) <= 9

I want my outputs to be like this

natural('05')
True

natural('asasassaas')
False

natural('243,432,355')
False

My question is how would i account for exponentially large numbers?

我认为您只是在寻找isdigit函数-它适用于您在此处列出的所有示例,并且用c编写,几乎可以肯定比纯python解决方案要快。

There is no need for you to do the additional check here:

and 0 <= int(x) <= 9

The isdigit method does this for you already. You pretty much want to stick with isdigit

Furthermore, a simplification can be made with the code where you can just stick to using isdigit like so:

def natural(x):
    return x.isdigit()

Thanks to @SteveJessop for the discussion on this.

You can loop over all characters in the provided string:

def natural(x):
    for c in x:
        if not c.isdigit():
            return False
    return True

This will stop once it encounters the first character that is not a digit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM