6

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
  • 217
  • 1
  • 2
  • 13

5 Answers5

18

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

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

jamylak
  • 120,885
  • 29
  • 225
  • 225
Meoiswa
  • 646
  • 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,491
  • 9
  • 59
  • 98
TerryA
  • 56,204
  • 11
  • 116
  • 135
  • (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
  • 29,514
  • 10
  • 78
  • 87
4

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
  • 447
  • 5
  • 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
  • 370
  • 3
  • 15