Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Addition assignment unable to concatenate strings?

Getting some odd behavior that I would like to have explained.

Here I am trying to concatenate multiple strings into a variable using +=

MyStr = ""
MyStr += "Hello ","Word"

But when I try to run it instead of concatenating I get this error:

Exception has occurred: TypeError
can only concatenate str (not "tuple") to str

After testing with strictly typed types and type identifiers I have come to the conclusion that += treats inputs as a tuple.

Why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

+= doesn’t treat input as tuples. The problem is that python treats "Hello", "World" as a tuple because they are multiple different objects which you are trying to group together. By default, python does this by creating a tuple.

Commas between strings work differently inside print statements, where the two are concatenated automatically by the print function.

So an easy fix should be:

MyStr = ""
MyStr += "Hello " + "World"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading