Python Concatenation

Concatenation is the process of combining multiple string (text) messages into one. For example if you have a variable with value “Hello ” and another variable with value “How are you?”. You can combine those two variables using concatenation. In Python concatenation is performed using the plus + sign

Example of Python concatenation:

In the above example, we are concatenating (combining) two variables (message1 and message2) string type values into one variable (finalMessage). Finally we are using print function to show the value of finalMessage.

Concatenation works great for text type data (strings), however if we try to combine a string with integer (number) type data then it would not work. The below code will produce an error.

The reason the above code will produce an error is because using the concatenation operator (+) we can not combine an integer (23) with a string (John). To achieve that we will use string format.

String Format

  • In Python string format allows combing strings with integers. This is also known as interpolation.
  • Python achieve this using a function named format.
  • String format syntax is very simple, we just need to place a place holder {}where would like our integers and then in format function we need to specify the name of the variables.

String format Syntax

“Some text here {}”.format(someVariable)

In the above syntax the format() method will replace the place holder of curly brackets {} with the value of someVariable.

We can also pass many variables to format function, for example in below syntax we are using two place holders and format function will replace them with two variables.

“Some text here {} some more text here {}”.format(someVariable1, someVariable2)

Example of string format in Python

In the above example we are showing a message and combining it with an integer 23 using format function. Format function will replace the empty curly brackets placeholder with the value of myAge variable.

Another example of string format

Another example of string format

In the older version of Python string format was achieved using a % sign. However, it’s deprecated now and we now use {} and format function in Python version 3 and upwards.

Here is an example of how interpolation was achieved in older python versions.

%s  was for Strings
%d was for Integers
%f – was Float

In Python 3 the % operator is deprecated and we now use {} placeholders and format function.