[Tutor] finding sum of digits in a string

Cameron Simpson cs at cskk.id.au
Mon Mar 14 18:53:58 EDT 2022


On 14Mar2022 21:38, Manprit Singh <manpritsinghece at gmail.com> wrote:
>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. Here I have to check all characters of the string one by one,
>why not use in operator as done in the 1st way. Any guidelines regarding
>this ?

Well, one could argue that each character _is_ a substring. What's the 
"should" mean here? Python does not have an individual character type, 
so substrings are what you get.

I prefer the second version as it clearly expresses the purpose of the 
test. The first version relies on the literal string-of-digits being 
correct, and a simple typo can lead to incorrect code.

And, in fact, your own code there _is_ incorrect, technically, though I 
suppose that adding "0" has no effect, so missing it out in the string 
still produces a correct result.

If I saw the first code I might _either_:
- miss the omission of "0" and read it as "all digits" i.e.  
  misunderstand the code
- or notice the missing "0" and spend time figuring out why you're using 
  some special subset of the digits and if that is important, either 
  directly here or elsewhere in the codebase
Either of those outcomes is unfortunate.

As usual, my advice is broadly: write the most readable code. The second 
clearly says "isdigit", which seems more readable to me.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list