[Tutor] Regex not working as desired
Peter Otten
__peter__ at web.de
Tue Feb 27 04:50:18 EST 2018
Alan Gauld via Tutor wrote:
> On 27/02/18 05:13, Cameron Simpson wrote:
>
>> hard to debug when you do. That's not to say you shouldn't use them, but
>> many people use them for far too much.
>
>
>> Finally, you could also consider not using a regexp for this particular
>> task. Python's "int" class can be called with a string, and will raise an
>> exception
>
> And, as another alternative, you can use all() with a
> generator expression:
>
>>>> all(c.isdigit() for c in '1234')
> True
>>>> all(c.isdigit() for c in '12c4')
> False
>>>>
>
> Or generally:
>
> def all_digits(s):
> return all(c.isdigit() for c in s)
Note that isdigit() already checks all characters in the string:
>>> "123".isdigit()
True
>>> "1a1".isdigit()
False
The only difference to your suggestion is how it handles the empty string:
>>> def all_digits(s):
... return all(c.isdigit() for c in s)
...
>>> all_digits("")
True
>>> "".isdigit()
False
A potential problem of str.isdigit() -- and int() -- may be its unicode
awareness:
>>> s = "\N{CHAM DIGIT ONE}\N{CHAM DIGIT TWO}\N{CHAM DIGIT THREE}"
>>> s
'꩑꩒꩓'
>>> s.isdigit()
True
>>> int(s)
123
More information about the Tutor
mailing list