Python

String Formatting With % Operator in Python

AKA.DM 2024. 10. 15. 07:40
반응형

The format is a method that helps us insert a variable or value anywhere in a string expression.

We can format using the percent sign.

For example, there is a sentence below. We would like to leave the blank in this sentence anonymous.

In other words, we do not want this empty part to remain costant ; we want to fill it with the vlaue we want in the next step.

 

So how do we do this? 

 

If we want to see a string value anonymously anywhere in a string expression, we need to use %s in the first step.

The letter "S" is the first letter of the string.

We put %s in the section below that we will fill with the value we want. 

Now let's examine how we can place the value we want in this section.

 

There are two print statements in the image below. 

We wnat to put the word "teachers" in the first blank and the word "chidren" in other.

To do this, we first call the variable. Then we use the percent sign and finally write expresison after the percent sign.

So that the blank part can be filled with a different value each time. 

 

If we wnated to use a integer value anonymously anywhere in a string expression, we need to use %d in the first step.

The letter "d" is the first letter of the "digit".

 

 

 

If we wnated to use a flaot value anonymously anywhere in a string expression, we need to use %f in the first step.

The letter "f" is the first letter of the "flaot".

 

While formatting float values, we can determine how many digits the decimal number will be. 

We write the number of digits we want by putting a period next to the percent sign.

If we wnat to the dicimal part to consist of 3 digits by saying %.3f below.

 

We can perform formatting using percentage operator together.

 

In % formatting, we can operate using the values we set in the value.

반응형