[Tutor] finding sum of digits in a string
Dennis Lee Bieber
wlfraed at ix.netcom.com
Mon Mar 14 21:13:59 EDT 2022
On Tue, 15 Mar 2022 09:53:58 +1100, Cameron Simpson <cs at cskk.id.au>
declaimed the following:
>>
>>1) sum(int(ele) for ele in st if ele in "123456789")
>>
>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.
>
I'd missed that on my first glance at the code (and I should note that
I've sort of started ignoring the OP -- 99% of their posts come down to
some trivial example that is highly unlikely to be seen in any actual
program, and the "question" is one of aesthetics/style, which is highly
subjective to the experience of the reader).
However, based upon https://docs.python.org/3/library/string.html, the
first version could be replaced with
import string
sum(int(ele) for ele in st if ele in string.digits)
>>> import string
>>> string.digits
'0123456789'
That avoids the "missing" digit ambiguity/error, along with the overhead of
call ele.isdigit() for each character in the input (after all, .isdigit()
probably does a loop over each character in "ele" and does the same "in
string.digits" test internally)
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
More information about the Tutor
mailing list