A way of checking if a string contains a number

Zero Piraeus schesis at gmail.com
Wed Dec 12 17:59:38 EST 2007


:

> [...] IMHO regular
> expressions are overkill for the task you describe.  You may be better served to
> just try to convert it to whatever number you want.
>
> try:
>      value=int(string1)

Fails for the OP's example:

  >>> string1 = "ABC 11"
  >>> int(string1)
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  ValueError: invalid literal for int(): ABC 11

> Or use string methods:
>
> if string1.isdigit():
>      print "digits found"
> else:
>      print "alphas found"

Again ...

  >>> string1.isdigit()
  False

If you were desperate to avoid regexes, this works:

  >>> max([(d in string1) for d in "0123456789"])
  True

... but it's not exactly legible.

 -[]z.



More information about the Python-list mailing list