Python: sum of digits in a string

I have a function I wrote for a project euler that calculates the sum of the digits in a number. This is my first attempt which simply converts each letter to an integer and sums them.

Method 1:

def digitsum(x):
	for letter in str(x):
	return total

I thought that this could be improved using ord, which converts a letter into its decimal ascii number. Numbers ‘0’, ‘1’, ‘2’ … ‘9’ correspond to the ascii values of 48 – 57 and then took the moduli of this with 48 to give the integer value. I later realised that this was completely nonsensical and should have just subtracted 48, but I decided to include it for the purposes of the speed test.

Method 2:

def digitsum2(x):
	for letter in str(x):
	return total 

Method 3:

def digitsum3(x):
	for letter in str(x):
	return total 

Speed Test:
The test uses a long number and one million repetitions for each method.

from time import time

# .. functions go here

# Nice long number to sum

tic = time()
for i in range(0,1000000):
print time() - tic, 'Seconds elapsed'

tic = time()
for i in range(0,1000000):
print time() - tic, 'Seconds elapsed'

tic = time()
for i in range(0,1000000):
print time() - tic, 'Seconds elapsed'


#Method 1
29.3496568203 Seconds elapsed
#Method 2
12.185685873 Seconds elapsed
#Method 3
9.59367895126 Seconds elapsed

So we can see that the first method is much slower, avoiding the integer conversion by using ord speeds it up the function by ~60% and that using subtraction rather than modulus (a division based operation) saves a further ~20% on top of this.


  1. l0nwlf

    sum(i for i in str(x))

    LC FTW!! 🙂

  2. mat

    I can see what your trying to do, but that will just cause an error as i is cast to the letters of str(x) which will be chars not ints, and you will get a type error when trying to sum chars.

  3. st0le


  4. kaj

    why not just use sum([int(k) for k in str(x)])

  5. Adela

    You completed various good points there. I did a search on the
    subject matter and found nearly all people will consent with
    your blog.

  6. BK

    I cant add the integers in the string (1,2,3,4,5,6)
    how do i do that?

Leave a Comment

Your email address will not be published. Required fields are marked *