3

What I want to do is to verify if a string is numeric -- a float -- but I haven't found a string property to do this. Maybe there isn't one. I have a problem with this code:

N = raw_input("Ingresa Nanometros:");
if ((N != "") and (N.isdigit() or N.isdecimal())):
    N = float(N);
    print "%f" % N;

As you can see, what I need is to take only the numbers, either decimal or float. N.isdecimal() does not resolve the problem that I have in mind.

jscs
  • 63,694
  • 13
  • 151
  • 195
p1r0
  • 418
  • 6
  • 10
  • 4
    The Python mantra is *'Ask for forgiveness, not permission.'* - try it, and catch the exceptions if it goes wrong. – Gareth Latty Feb 19 '13 at 02:11
  • 1
    If you want to know why your code doesn't work: `N.isdigit()` is true if every character in `N` is a digit. That isn't true for `3.14`. You're asking "Is every character a digit, or is every character a decimal?" when you want to ask "Is each character either a digit or a decimal", which would be spelled `all(ch.isdigit() or ch.isdecimal() for ch in N)`. Of course that still won't work for, say, `-3.14` or other perfectly valid `float`s. That's one of the many reasons that "Easier to Ask Forgiveness than Permission" is the "One Way To Do It"—but it's still worth understanding `isdigit`. – abarnert Feb 19 '13 at 02:29

1 Answers1

10
try:
    N = float(N)
except ValueError:
    pass
except TypeError:
    pass

This tries to convert N to a float. However, if it isn't possible (because it isn't a number), it will pass (do nothing).

I suggest you read about try and except blocks.

You could also do:

try:
    N = float(N)
except (ValueError, TypeError):
    pass
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94