Search code examples
python-3.xtuplesconcatenation

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?


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"