Why does + (plus) can concatenate two strings in Python?

python append to string in loop
python string concatenation
3.1.2 concatenating strings
python concatenate string and variable
python string
how to concatenate two strings with space in python
python concatenate two variables
how to concatenate two strings in python without space

I'm learning Learn Python the hard way.

w = "This is the left side of..."
e = "a string with a right side."
print w + e

Explain why adding the two strings w and e with + makes a longer string.

Even I know it can work, but I don't understand why and how? Please help me.

Python uses + to concatenate strings because that's how core developers of Python defined that operator.

While it's true that __add__ special method is normally used to implement the + operator, + (BINARY_ADD bytecode instruction) does not call str.__add__ because + treats strings specially in both Python 2 and Python 3. Python invokes the string concatenation function directly if both operands of + are strings, thus eliminating the need to call special methods.

Python 3 calls unicode_concatenate (source code):

TARGET(BINARY_ADD) {
    PyObject *right = POP();
    PyObject *left = TOP();
    PyObject *sum;
    if (PyUnicode_CheckExact(left) &&
             PyUnicode_CheckExact(right)) {
        sum = unicode_concatenate(left, right, f, next_instr);
        /* unicode_concatenate consumed the ref to v */
    }
    else {
        sum = PyNumber_Add(left, right);
        Py_DECREF(left);
    }
    ...

Python 2 calls string_concatenate (source code):

case BINARY_ADD:
    w = POP();
    v = TOP();
    if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
        /* INLINE: int + int */
        register long a, b, i;
        a = PyInt_AS_LONG(v);
        b = PyInt_AS_LONG(w);
        /* cast to avoid undefined behaviour
           on overflow */
        i = (long)((unsigned long)a + b);
        if ((i^a) < 0 && (i^b) < 0)
            goto slow_add;
        x = PyInt_FromLong(i);
    }
    else if (PyString_CheckExact(v) &&
             PyString_CheckExact(w)) {
        x = string_concatenate(v, w, f, next_instr);
        /* string_concatenate consumed the ref to v */
        goto skip_decref_vx;
    }
    else {
      slow_add:
        x = PyNumber_Add(v, w);

    ...

This optimization has been in Python ever since 2004. From the issue980695:

... in the attached patch ceval.c special-cases addition of two strings (in the same way as it special-cases addition of two integers already)

But note that the main goal was greater than elimination of special attribute lookup.


For what it's worth, str.__add__ still works as expected:

>>> w.__add__(e)
'This is the left side of...a string with a right side.'

and Python will call __add__ methods of subclasses of str, because PyUnicode_CheckExact(left) && PyUnicode_CheckExact(right) (or PyString_CheckExact(v) && PyString_CheckExact(w), in Python 2) from the code snippets above will be false:

>>> class STR(str):
...     def __add__(self, other):
...         print('calling __add__')
...         return super().__add__(other)
... 
>>> STR('abc') + STR('def')
calling __add__
'abcdef'

Splitting, Concatenating, and Joining Strings in Python – Real Python, The best way to describe it is when you take two separate strings – stored by the This post will describe how to concatenate strings in Python. You cannot concatenate a string and a number (of any kind) in python because those objects have different definitions of the plus(+) operator which are not compatible with each other (In the str case + is used for concatenation, in the number case it is used to add two numbers together).

The __add__ method of the class str is called when you add (concatenate) two strings in this manner. The __add__ method works as such, but the following is not verbatim from the source code:

def __add__(self, str1, str2):
    str3 = [str1] #Convert to list
    str3.append(str2) #Add the second string to the list
    return ''.join(str3) #Return the two joined

Example:

class MyString:
    def __init__(self, initstr):
        self.string = initstr
    def __add__(str1, str2):
        str3 = [str1.string] #Convert to list
        str3.append(str2.string) #Add the second string to the list
        return MyString(''.join(str3)) #Return the two joined

>>> a = MyString("Hello")
>>> b = MyString(" World!")
>>> c = a+b
>>> c.string
'Hello World!'
>>> 

String Concatenation and Formatting, In Python, using plus signs to concatenate strings together is one of the first things What can look very similar will yield two different results: Concatenation of strings have the disadvantage of needing to create a new string and allocate new memory for every concatenation! This is time consuming, but isn't that big of a deal with few and small strings. When you know the number of strings to concatenate and don't need more than maybe 2-4 concatenations I'd go for it.

+, -, *, and other operators will work on anything that implements the right methods. Since strings implement the __add__(self, other) method, you can add two strings with +.

Try this: define your own string subclass and override its __add__ method:

class BadString(str):
    def __add__(self, other):
        # Ignore both input strings and just return this:
        return "Nothing Useful"

s = BadString("hello")

print("hello" + " world")    # "hello world"
print(s + "world")           # "Nothing Useful"

The same technique, operator overloading, lets you create classes that can use the built-in operators like + or * usefully, like vectors that can be added together.

Stop using plus signs to concatenate strings!, Let's look at another example where we will get two strings from user input and concatenate them. s1 = input('Please enter the first string:\n') s2  Also, in Python, %s syntax will automatically coerce any non str types to str; while concatenation only works with str, and you can't concatenate str with int. Performance. In Python str is immutable, so the left and right string have to be copied into the new string for every pair of concatenation. If you concatenate four strings of length 10, you will be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters, instead of just 40 characters.

Python String Concatenation, Python Concatenate String and int, Python String concat with int, How to In most of the programming languages, if we concatenate a string with an However, in Python, if you try to concatenate string and int using + operator, you will get a  In your second example, you're passing five arguments to print.print will then automatically convert all of its arguments to strings and print them separated with spaces. . In your first example, you're building up one big string, and then passing it as a single argument to pri

Python Concatenate String and int, This is because Python will evaluate a variable to the value stored inside it: in this case, The + operator can concatenate two string values into a new string value we use the plus operator (+) to concatenate the string 'It is good to meet you,  Python uses + to concatenate strings because that's how core developers of Python defined that operator. While it's true that __add__ special method is normally used to implement the + operator, + ( BINARY_ADD bytecode instruction ) does not call str.__add__ because + treats strings specially in both Python 2 and Python 3.

String and Writing Programs, Here, we will learn how to concatenate two strings using + (plus) operator and assign the result to another string in Python? We can perform concatenation in Python by adding a plus(+) symbol between strings. When we concatenate you may want to plan ahead and add a space at the end of the original string or add a space

Comments
  • Why does this surprise you any more than the fact that + can add two numbers? That's just how Guido defined Python's + operator.
  • Explain why adding the two strings w and e with + makes a longer string. - What else do you expect?
  • Wait till you get to 'Hello' * 3