Skip to content
Advertisement

Python: Sum string lengths

Is there a more idiomatic way to sum string lengths in Python than by using a loop?

length = 0
for string in strings:
    length += len(string)

I tried sum(), but it only works for integers:

>>> sum('abc', 'de')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

Advertisement

Answer

I know this is an old question, but I can’t help noting that the Python error message tells you how to do this:

TypeError: sum() can't sum strings [use ''.join(seq) instead]

So:

>>> strings = ['abc', 'de']
>>> print len(''.join(strings))
5
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement