A way of checking if a string contains a number

MRAB google at mrabarnett.plus.com
Wed Dec 12 20:27:39 EST 2007


On Dec 12, 10:59 pm, "Zero Piraeus" <sche... at gmail.com> wrote:
> :
>
> > [...] 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.
>

How about:

>>> string1 = "ABC 11"
>>> any(c.isdigit() for c in string1)
True



More information about the Python-list mailing list