Shorter way to check if isdigit () string is

For training, there is a shorter way to do: if string.isdigit() == False :

I tried: if !string.isdigit() : and if !(string.isdigit()) : which both didn't work.

+4
source share
4 answers

The Python operator is not , not ! .

The logical not operator is Python not , not ! .

+11
source

In python instead ! the not keyword is used:

 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 :

Do not compare booleans with True or False using ==.

Yes: if greeting:

No: if greeting == True

Worse: if the greeting is True:

+11
source
 if not my_str.isdigit() 

Also, do not use string as the name of a variable, as it is also the name of a commonly used standard module.

+6
source

string.isdigit (g) returns False if g is negative or floats. I prefer to use the following function:

 def is_digit(g): try: float(g) except ValueError: return False return True 
0
source

All Articles