Generic selectors
Exact matches only
Search in title
Search in content
wb_sunny

String Formatting in Python – A Quick Overview

String Formatting Title

String formatting, as the name suggests, refers to the multiple ways to format strings in Python. In this tutorial, we will discuss the different ways and how to use them.

What is String Formatting?

Let us say you are writing a program that prints the square of a number. In your input, you get an integer from the user, and in the output, you tell the user that the square of the integer is so and so.

For Example, if the input is 12, then you’ll need to print “The square of 12 is 144”. We cannot write a complete string like this because we have two integers to insert in the string, so we will need a way to generate this string. String formatting allows us to do that.

Note: If we do print("The square of", input, "is", result), this will print four different things, it will not generate a formatted string, so this doesn’t count as string formatting.

Types of String Formatting Techniques

Today we will be discussing three ways of formatting strings:

  1. Using the % operator
  2. Using f-strings
  3. Using the format() method

Let us discuss each method one by one.

1. String Formatting Using The % Operator

This is an old way for string formatting is still useful for simple operations. This works very similarly to the printf statement in C.

Let us take an example:

num = 12
result = num * num
str = "The square of %d is %d" % (num, result)
print(str)

The Output:

The square of 12 is 144

We have two integers, num and result. In the double quotes, we are writing the entire string that is to be printed, but instead of the integers, we are writing %d. This will tell Python that an integer is to be substituted here.

After the string, we use the % operator and write the second operand which is a tuple containing the list of integers to be substituted in the correct order. In the above example, we have two integers to be substituted, so we write the two integers in a tuple and put it as the second operand.

Notice that inside the string we have written %d, whatever comes after % is called the format specifier. In the example, d is the format specified for integers, s for strings, f for float or decimal, etc. To see the full list of specifiers, we can see the Python docs.

Tips for using % for formatting strings

  1. We can specify a number between % and the format specifier (e.g. %5d), and Python will give the integer left padding so that the total number of character the integer takes is equal to the number specified. In case of %5d, “123” will be substituted as ” 123″, 12 is substituted as ” 12″, etc.
  2. The above number can be specified with a zero on the left side (e.g. %05d), and Python will give the integer similar left padding but instead of spaces, it will have zeroes. For example, In the case of %05d, “123” will be substituted as “00123”, “12” will be substituted as “00012”, etc.
  3. The above number can also be specified with a “-” sign on the left side (%-5d), and instead of providing left padding, Python will provide padding on the right side. So, for %-5d, “123” will be substituted as “123 “, “12” will be substituted as “12 “, etc.

These points can come in handy when a table is to be constructed.

2. Formatting using f-strings

This is the easiest to understand, and most widely used formatting technique. To understand it, let us take an example.

num = 12
result = num * num
str = f"The square of {num} is {result}"
print(str)

Output:

The square of 12 is 144

As you can see, we directly embed the expressions inside the string. The string is also prefixed by the letter “f”, and this will tell python that it is an f-string and whatever expression is written inside { and } is to be evaluated and embedded into the string at that position.

The expression inside the curly brackets need not be a single variable, rather, it can be any statement that returns a value. It can be an arithmetic calculation, a function call, or a conditional operation. Let us see an example:

a = 1
b = 2
str = f"Expression: {a + b}"
print(str)

Output:

Expression: 3

In the above example, we perform a mathematical operation inside the f-string. So we can see that f-strings are powerful options.

Let us see another example:

a = 1
b = 2
str = f"a is '{a:5}' and b is '{b:05}'"
print(str)

Output:

a is '    1' and b is '00002'

Similar to the % operator, here also we can specify paddings as shown in the above example.

3. String Formatting using the .format() method

This method is very similar to f-strings, let us see it using an example:

num = 12
result = num * num
str = "The square of {} is {}".format(num, result)
print(str)

Output:

The square of 12 is 144

As we can see, inside the string we specified two placeholders using {}, and then we use the format method on the string, and pass the appropriate integers to be replaced in the correct order.

We can put identifiers inside the curly brackets, but we will have to send values for the identifiers later. We can also specify left padding like we did earlier. Take this example:

a = 1
b = 2
str = "a is '{first}' and b is '{second:03}'".format(first=a, second=b)
print(str)

Output:

a is '1' and b is '002'

In the above example, we put names inside the placeholders, and in the format method’s argument list, we specified the value for each placeholder using its name. The second placeholder is even been specified with zero paddings on the left as in the other techniques.

Conclusion

In this tutorial, we studied string formatting and we discussed three common ways of doing it. We studied the % operator first, then we moved on to f-strings and the format method. We also discussed how to add padding to formatted strings and we studied the code by seeing its output.

Hope you had a great time learning and see you in the next tutorial.