[Tutor] Regex not working as desired

Alan Gauld alan.gauld at yahoo.co.uk
Tue Feb 27 06:59:50 EST 2018


On 27/02/18 09:50, Peter Otten wrote:
>> def all_digits(s):
>>     return all(c.isdigit() for c in s)
>  
> Note that isdigit() already checks all characters in the string:

Ah! I should have known that but forgot.
I think the singular name confused me.

> 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

Interesting, I'd have expected all() to return
False for an empty sequence... But looking at help(all)
it clearly states that it returns True. RTFM! :-(

However, in practice, and for this specific case, the
try/except route is probably best, I just wanted to
point out that there were other (concise) ways to
avoid a regex.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list