How to Use Placeholders in Python



Python


In this article, we show how to use placeholders in Python to serve as placeholders for data, such as objects.

So if you have a variable in Python or any other type of data type, you can create a placeholder, usually in a print function to reserve a spot for this variable before explicitly saying what the variable is.

The best way to see this is in actual code.

In the code below, we create 2 variables, desination1 and destination2.

We then print out these variables with a print function using placeholders.

You'll see exactly how this works below.



So, the above code is very simple.

We create 3 variables.

The first variable we create is destination1. We set this variable equal to "beach"

The second variable we create is destination2. We set this variable equal to "park"

The third variable we create is amount. We set this variable equal to 3.

We then create a print statement.

Every time you see {} in the print statement, this represents a placeholder.

What a placeholder does is it holds a place for a variable. When we do the substition, the variable will appear in the place of {}.

You see this 3 times in the print statement, meaning 3 places for variables are reserved.

After we are done with the print statement ending with quotes (either single or double), we put .format(destination1, destination2, amount), representing the 3 variables in order that we want substituted for the placeholders.

In the end, this gives us the output statement, " I went to the beach and park 3 times this week"

Placeholders are great things to use in Python code especially if you are dealing with different types of data.

For example, to create this same method the conventional way without placeholders, we would have the following print line, shown below.



You can see what an extreme pain this is.

There's a lot of annoyances.

One thing is, we have to keep breaking the string apart every time we want to put in a variable.

Second, we have to remember to put appropriate spaces between variables, which can be very annoying.

Lastly, for strings taking in different data types, such as int, we have to explicitly make the variable a string with the str() function, or else Python will throw an error.

So there's a lot of annoyances.

With placeholders, all of this foregone.

You simply put the placeholder, without any care to the different data types, close the string, put . format() with the names of the variables within the format function, and that is it.

So this is just a quick guide on the value of placeholders in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...