为什么Python中禁止对字符串使用sum函数?
sum() fails with string lists in Python At first glance, it makes total sense to assume any object with an __add__ method should work with sum()—and strings do implement __add__ for concatenation:
"abc" + "def" # Returns "abcdef"
But here's the key detail that trips things up: sum() uses a default starting value of 0 (an integer). You can confirm this with quick tests:
sum([]) # Output: 0 sum([], 7) # Output: 7
So when you run sum(["abc", "def"]), Python is actually doing this under the hood:
- Start with the default value
0 - Try to add the first string:
0 + "abc"
That's exactly why you get the error:
sum(["abc", "def"]) # Throws TypeError: unsupported operand type(s) for +: 'int' and 'str'
For what it's worth, you can force sum() to work for strings by passing an empty string as the starting value:
sum(["abc", "def"], "") # Returns "abcdef"
But a quick heads-up—don’t use this in real code. str.join() is purpose-built for string concatenation and is way more efficient, especially with large lists.
内容的提问来源于stack exchange,提问作者patapouf_ai

