For the sake of learning, is there a shorter way to do:
if string.isdigit() == False :
I tried:
if !string.isdigit() :
and if !(string.isdigit()) :
which both didn't work.
For the sake of learning, is there a shorter way to do:
if string.isdigit() == False :
I tried:
if !string.isdigit() :
and if !(string.isdigit()) :
which both didn't work.
Python's "not" operand is not
, not !
.
Python's "logical not" operand is not
, not !
.
In python, you use the not
keyword instead of !
:
if not string.isdigit():
do_stuff()
This is equivalent to:
if not False:
do_stuff()
i.e:
if True:
do_stuff()
Also, from the PEP 8 Style Guide:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True
Worse: if greeting is True:
if not my_str.isdigit()
Also, don't use string
as a variable name as it is also the name of a widely used standard module.
maybe using .isalpha() is an easier way...
so; instead of if not my_str.isdigit()
you can try if my_str.isalpha()
it is the shorter way to check if a string is not digit
string.isdigit(g) returns False if g is negative or float. I prefer using following function:
def is_digit(g):
try:
float(g)
except ValueError:
return False
return True
The (!) only works when saying something does not equal something else (!=).
if str.isdigit() != True:
It doesn't make much sense to do it that way because you can just say equals True.
if str.isdigit() == False:
You could also just use not instead of (!).
if not str.isdigit():
Note: this will only work if the string is an integer, it will return false even if it is an integer written as a float (i.e. '1.0'). To check if a string is a number of any kind try this function...
def is_digit(str):
try:
float(str)
except ValueError:
return False
return True