String Concatenation and String Arithmetic in Python


String concatenation and other string arithmetic is a small nuance of programming, that often may be discovered by a new programmer on accident. This is because, as covered in the arithmetic article here, string concatenation can often happen when a programmer is trying to perform ordinary arithmetic. The problem is that string concatenation occurs when arithmetic, specifically adding, is performed between two strings. If you need to read up about types, read the article here. In this article, we will look at concatenation and other arithmetic between strings.

String Concatenation

String concatenation is essentially sticking two strings together. This is performed with the addition operator. This is specifically different than normal addition. As we can see, here is normal arithmetic in python.



We can see the math that is performed here. However, if we change the integers, which are the number twos, to strings, something else happens.



Because the things being added are strings, denoted by the quotation marks, they are not added mathematically, even though they are numbers. If they have quotation marks around them, adding them results in concatenation. Another example:





As you can see, this works the same between two strings with letters. Here, we created a variable holding a string. We then added another string onto it, altering it's value. So, any strings added together, will result in concatenation.

Note: Adding a string with another data type will result in a type error!

String Multiplication

Another operation that can be performed in Python on strings is string multiplication. This is actually performed between a string and an integer. Observe:






As can be seen, multiplying strings essentially multiplies the number of times they occur.


This is a small idea, but one that may come in handy when handling data. You never know what you may need to do in programming, so mastering as many skills as possible is best.