7

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.

Nick Rutten
  • 227
  • 1
  • 2
  • 13

6 Answers6

20

Python's "not" operand is not, not !.

Python's "logical not" operand is not, not !.

jamylak
  • 128,818
  • 30
  • 231
  • 230
Meoiswa
  • 666
  • 4
  • 12
  • 2
    But it's `not` my fault! In all seriousness, that's why I used the quotes, code notation and normal form to differentiate – Meoiswa May 02 '13 at 10:37
15

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:

Stephen
  • 18,827
  • 9
  • 60
  • 98
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • (Off-topic: Anyone else thinks that `is True` is not *worse* than `== True`, but rather the other way around?) – poke May 02 '13 at 10:45
  • 1
    @poke http://stackoverflow.com/questions/4591125/is-it-safe-to-replace-with-is-to-compare-boolean-values – TerryA May 02 '13 at 10:46
7
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.

Volatility
  • 31,232
  • 10
  • 80
  • 89
5

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

msklc
  • 553
  • 1
  • 8
  • 10
0

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
Anton
  • 420
  • 5
  • 15
0

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