String Formatting in Python

String formatting plays an important role when storing and transferring data in a way that anyone can easily understand. If you are new to the Python programming language and don’t know how to format strings to display the output, this article is for you. In this article, I’ll walk you through how to do string formatting in Python.

What is String Formatting in Python?

String formatting is one of the ways to format the output. Here we are using pairs of curly braces that are replaced with arguments in the order in which the arguments are supposed to be passed when displaying the output to a user. Formatting strings to display the output is also known as f-strings because we need to prefix a string with the letter “f” to format the output.

There are several ways to format strings. Below are the most important options you can use to format strings to display the output:

  1. <“: This forces the field to be left-aligned in the available space.
  2. >“: This forces the field to be right-aligned in the available space.
  3. =“: It forces the padding to be placed after the sign but before the numbers.
  4. ^“: It forces the field to be centred in the available space.
  5. f“: It displays the number as a fixed-point number.
  6. %“: It multiplies the number by 100 and displays in the fixed format (“f”), followed by a % sign.

String Formatting in Python

I hope you now have understood what is strings formatting. Now let’s have a look at how to format strings in Python by using an example. There are two common ways for formatting strings to display the output, let’s go through both of them one by one:

Output:
Your Name is Aman, and your age is 22

In the above code, I replaced the curly brackets with the values of the Name and Age variables by using the str.format method. The other way of doing the same task is shown below:

Output:
Your Name is Aman, and your age is 22

In the code above, I used the f-strings method which displays the values the same way they were assigned.

Also, Read – Python Projects with Source Code.

Summary

String formatting plays an important role when storing and transferring data in a way that anyone can easily understand. Here we are using pairs of curly braces that are replaced with arguments in the order in which the arguments are supposed to be passed when displaying the output to a user. I hope you liked this article on string formatting with Python. Feel free to ask your valuable questions in the comments section below.

Default image
Aman Kharwal

Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder

Articles: 997

Leave a Reply