Python: Sum string lengths

2019-04-19 11:05发布

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]

标签: python list sum
7条回答
我只想做你的唯一
2楼-- · 2019-04-19 11:53

Here's another way using operator. Not sure if this is easier to read than the accepted answer.

import operator

length = reduce(operator.add, map(len, strings))

print length
查看更多
我想做一个坏孩纸
3楼-- · 2019-04-19 11:54
length = sum(len(s) for s in strings)
查看更多
放荡不羁爱自由
4楼-- · 2019-04-19 11:59
print(sum(len(mystr) for mystr in strings))
查看更多
Summer. ? 凉城
5楼-- · 2019-04-19 12:00

Just to add upon ...

Adding numbers from a list stored as a string

nos = ['1','14','34']

length = sum(int(s) for s in nos)

查看更多
叼着烟拽天下
6楼-- · 2019-04-19 12:01

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
查看更多
【Aperson】
7楼-- · 2019-04-19 12:01

My first way to do it would be sum(map(len, strings)). Another way is to use a list comprehension or generator expression as the other answers have posted.

查看更多
登录 后发表回答