Python Forum

Full Version: How to sum up the elements of an integer using python split/join?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to sum up the elements of an integer using python split join
Here is my code,
-----------------------
a='1234'
b=list(a)
c='+'.join(b)
print© ##output- 1+2+3+4
-------------------------------------
How to get the sum of all the elements
Do you want "sum up the elements of an integer" or "sum up the elements of an integer using python split join"?

What is expected outcome? 1 + 2 + 3 + 4 = 10 or 1 + 2 + 3 + 4 = 10 --> 1 + 0 = 1
Thanks for you reply.
i want the output like this 1+2+3+4= 10
Still, output should be '1 + 2 + 3 + 4 = 10' or just '10'?

You can have this way:

>>> a = '1234' 
>>> b = list(a)
>>> total = sum([int(x) for x in b]) 
>>> f"{' + '.join(b)} = {total}"
'1 + 2 + 3 + 4 = 10' 
Or just sum:

>>> a = '1234'
>>> sum([int(x) for x in list(a)])
10
Thanks a lot perfringo!!
You are welcome!

Some observations and for future references.

It is very important to have correct name for thread. Currently it reads "How to sum up the elements of an integer using python split/join?" and there are several problems with that: there is no elements in integer as integer is not iterable; integer does not support split/join. Problem is actually about string which looks like integer.

If somebody searches for solution how sum up digits in integer and reaches this thread will be disappointed that despite promising name it's about something else (of course, one can always do str(1234) and use code above).

For those, who looking for "how to sum up digits in integer" without converting into string:

1. Only digits which are at display (shallow sum) i.e 149 = 1 + 4 + 9 = 14. This solution relies of Python feature that in truth value testing zero of any numeric type is false

def sum_digits(i):
    total = 0
    while i:
        total += i % 10
        i //= 10
    return total
2. Sum integer digits until there is only one digit (deep sum), i.e 149 --> 1 + 4 + 9 = 14 --> 1 + 4 = 5 This relies on math concept of modulo 9 and not any specific Python feature:

def sum_digits(i):
    return (i - 1) % 9 + 1
If modulo 9 concept seems foreign one can use shallow sum recursively to have deep sum:

def sum_digits(i):
    total = 0
    while i:
        total += i % 10
        i //= 10
    if total < 10: 
        return total
    else:
        return sum_digits(total)