简体   繁体   中英

How would I account for negative values in Python?

I am trying to see if a string (it has to be a string) is a number.

So far I am using isdigit() but apparently isdigit does not account for negative numbers.

If I do isdigit(a) and a = -1 I get False.

If I do isdigit(a) and a = 1 I get True.

So far I have,

def rotationKeyValidated(rotationKeyStr):
    if rotationKeyStr.startswith('-') and rotationKeyStr[1:].isdigit():
        int(rotationKeyStr)
    return rotationKeyStr.isdigit()

I am trying to see if it starts with a negative sign, and the rest is a digit then well.. I don't know because I don't want to use multiple return statements.

You can use a try/except block and attempt to convert the string into an integer:

def rotationKeyValidated(rotationKeyStr):
    try:
        int(rotationKeyStr)
    except ValueError:
        return False
    return True

This style of coding embraces Python's EAFP principle and is preferred by most Python programmers. It is also quite robust, handling any string that can be converted into an int .


Since your assignment requires only one return-statement, you can add an else: block and a flag:

def rotationKeyValidated(rotationKeyStr):
    try:
        int(rotationKeyStr)
    except ValueError:
        flag = False
    else:
        flag = True
   return flag

The else: block will only be executed if the try: block executes without raising an error.


Well, since you must use str.isdigit , you could always do something like this:

def rotationKeyValidated(rotationKeyStr):
    if rotationKeyStr.startswith('-'):
        rotationKeyStr = rotationKeyStr[1:]
    return rotationKeyStr.isdigit()

The if-statement checks if the string starts with - and removes that character if so. After that, we can safely return the result of str.isdigit .

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