Learn Concatenation and Interpolation with Python Strings

Jeffrey Martinez
3 min readDec 15, 2021

Learn the difference between string interpolation and concatenation in Python

Objectives:

  • Learn about string concatenation and implementation
  • Learn string interpolation and implementation

What is String Concatenation?

In python, concatenation means the “joining” of strings together using the + operator. What we have to watch out for, is that if the parameters/variables passed are similar in data type, then the concatenation would be performed. In other words, if we have two variables, that are both strings, then we would not get an error. But if we had one variable as an integer, and one variable assigned to a string, then Python will report an error condition.

Let’s take a look at an example:

We created two variables in python and assigned them to be strings. We created another variable “result” that is going to concatenate the “first” variable, add a space in the middle, and add the “second” variable. Thus, our output would be “Hello World”. Seems simple enough right?

Can you imagine concatenating so many spaces, maybe even a welcoming message that includes your first and last name. Is there another way we can add strings together to become a single phrase? Well, there is a way! Let’s take a look at string interpolation!

What is string interpolation?

According to Programiz.com , string interpolation is a process substituting values of variables into placeholders in a string. Thankfully, Python 3 has made it easier for us to combine variables to a single string without adding the + operator. Python 3.6 added a new literal prefix f that will be used in order for us to interpolate variables.

Let’s take a look at it’s syntax

We have created two variables that are assigned to a first name and a last name. In order for us to string interpolate, we have to use an f string whose syntax is as follows: f" {} " where anything inside the curly bracket would be a variable you would like to use. As you can see within the above example, result, is assigned to a string interpolation of a string that includes the first_name and last_name variables. Thus, our outcome would return “Welcome, Jeffrey Martinez! How are you today”.

Literal String Interpolation method is powerful interpolation method which is easy to use and increase the code readability.

Resources:

Make sure to take a look at these resources that talk about string concatenation, and string interpolation!

--

--

Jeffrey Martinez

I am a graduate from Flatiron School for Software Engineer. Studied HTML, CSS, Ruby, Ruby on Rails, JavaScript, React, Redux, Sinatra, and Sqlite3