[Tutor] finding sum of digits in a string

Alan Gauld alan.gauld at yahoo.co.uk
Mon Mar 14 20:41:11 EDT 2022


On 14/03/2022 16:08, Manprit Singh wrote:
> Dear Sir,
> 
> Take an example of finding the sum of digits in a string :
> 
> st = "ab23YH6UJ7ik83LO"
> 
> To find the sum of digits in the string st, i can do it in below given
> manners :
> 
> 1) sum(int(ele) for ele in st if ele in "123456789")
> 
> 2) sum(int(ele) for ele in st if ele.isdigit())
> 
> Although the 2nd one is more compact, using isdigit() method , what bothers
> me is - isdigit() method. It should be used to check a substring, not a single
> character. 

A single character is a substring. And there is no dedicated
method for checking single characters as a special case.

> why not use in operator as done in the 1st way.

Because it iterates over the list of numbers meaning, on
average 5 tests for each character. Now isdigit() might
do that too but I hope not!

You might improve things by using a set instead of a
string - the set inclusion operator should theoretically
be faster than an 'in' search. But as always with performance
test to see...

But the most important reason, as always, is readability.
isdigit() clearly expresses what you want to do. (Although
you may want to consider whether you really want isdecimal()
or isnumeric() instead. I suspect isdecimal() suits you
best here.)



-- 
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