Is there a more idiomatic way to sum string lengths in Python than by using a loop?
JavaScript
x
4
1
length = 0
2
for string in strings:
3
length += len(string)
4
I tried sum()
, but it only works for integers:
JavaScript
1
5
1
>>> sum('abc', 'de')
2
Traceback (most recent call last):
3
File "<stdin>", line 1, in <module>
4
TypeError: sum() can't sum strings [use ''.join(seq) instead]
5
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:
JavaScript
1
2
1
TypeError: sum() can't sum strings [use ''.join(seq) instead]
2
So:
JavaScript
1
4
1
>>> strings = ['abc', 'de']
2
>>> print len(''.join(strings))
3
5
4