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: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:The
else:
block will only be executed if thetry:
block executes without raising an error.Well, since you must use
str.isdigit
, you could always do something like this:The if-statement checks if the string starts with
-
and removes that character if so. After that, we can safely return the result ofstr.isdigit
.