1-26-2021
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 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.
print(2+2)
4
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.
print("2"+"2")
"22"
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:
word="a"
word+="b"
print(word)
"ab"
Another operation that can be performed in Python on strings is string multiplication. This is actually performed between a string and an integer. Observe:
print("4"*3)
"444"
fav_num="23"
fav_num*=4
print(fav_num)
"23232323"
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.