Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

string concatenation via `sum` #1632

Closed
Phillip-M-Feldman opened this issue Sep 7, 2020 · 4 comments
Closed

string concatenation via `sum` #1632

Phillip-M-Feldman opened this issue Sep 7, 2020 · 4 comments

Comments

@Phillip-M-Feldman
Copy link

@Phillip-M-Feldman Phillip-M-Feldman commented Sep 7, 2020

I'm not sure whether this is a bug or a feature request, but it seems as though the following should produce the same result:

In [1]: 'a' + 'b' + 'c'
Out[1]: 'abc'

In [2]: sum(('a', 'b', 'c'))

TypeError Traceback (most recent call last)
in
----> 1 sum(('a', 'b', 'c'))

TypeError: unsupported operand type(s) for +: 'int' and 'str'

The error message is confusing (there is no integer).

@hugovk
Copy link
Contributor

@hugovk hugovk commented Sep 7, 2020

This is the repository and issue tracker for the https://www.python.org website.

If you're looking to file an issue with CPython itself, please go to https://bugs.python.org

@shreyansh-kushwaha
Copy link

@shreyansh-kushwaha shreyansh-kushwaha commented Oct 19, 2020

Hey dear
Try storing the string into a variable first and then try to add them...
This might help you
Thanks ;)

@shreyansh-kushwaha
Copy link

@shreyansh-kushwaha shreyansh-kushwaha commented Oct 19, 2020

But if it still not works then I think that the sum () function can only add integers and floats

@berkerpeksag
Copy link
Member

@berkerpeksag berkerpeksag commented Oct 19, 2020

It's because result is set to 0 here: https://github.com/python/cpython/blob/985f0ab3ad5e8e9a8d7fc53026c38390b1f2b466/Python/bltinmodule.c#L2296

Then Python basically tries to do:

result = 0
for item in ('a', 'b', 'c'):
    result += item

You can create a bug report at bugs.python.org and ask if it's possible to improve error message, but I'd expect it's going to be rejected since it's a rare usage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants
You can’t perform that action at this time.