Format function in Python
By: Sunil Kumar
Tags: Python, Data Science, Software Engineering, Programming, Software Development

Python’s str.format() technique of the string category permits you to try and do variable substitutions and data formatting. This enables you to concatenate parts of a string at desired intervals through point data format.

This article can guide you through a number of the common uses of formatters in Python, which may help your code and program to be user friendly.

1) Single Formatter:

Formatters work by fixing one or a lot of replacement fields or placeholders outlined by a pair of curled brackets “{}” — into a string and calling the str.format() technique. You’ll pass into the format() method the value you wish to concatenate with the string. This value will be printed in the same place that your placeholder {} is positioned once you run the program. Single formatters can be defined as those where there is only one placeholder. In the below example you can see the implementation of format in the print statement.

print("{} is a good option for beginners in python".format("Research Papers")) OUTPUT:

Research Papers is a good option for beginners in python

Apart from directly using it in the print statement, we can also use format() to a variable

my_string = "{} is a good option for beginners in python"print(my_string.format("Research Papers")) OUTPUT:

Research Papers is a good option for beginners in python

2) Multiple Formatter:

Let’s say if there is another variable substitution required in a sentence, this can be done by adding a second curly bracket where we want the substitution and passing a second value into format(). Python will then replace the placeholders by values that are passed in the inputs.

my_string = "{} is a good option for beginners in {}"

print(my_string.format("Research Papers","Machine Learning")) OUTPUT:

Research Papers is a good option for beginners in Machine Learning

We can add any number of placeholders or curly brackets that we require in a given variable along with the same number of inputs for the format().

my_string = "{} is an {} option for {} in {}"

print(my_string.format("Research Papers","excellent","experienced","Machine Learning")) OUTPUT:

Research Papers is an excellent option for experienced in Machine Learning

3) Formatters using Positional and Keyword Arguments:

When placeholders are empty {}, Python interpreter will be replacing the values through str.format() in order.

The values that exist among the str.format() method are primarily tuple (“A tuple is a sequence of immutable Python objects”) data types and every individual item contained within the tuple are often referred by its index number, which starts with zero. These index numbers are then passed into the curly brackets within the original string.

You can use the positional arguments or the index numbers inside the curly brackets in order to get that particular value from the format() into your variable:

my_string = "{0} is a good option for beginners in {1}"

print(my_string.format("Research Papers","Machine Learning")) OUTPUT:

Research Papers is a good option for beginners in Machine Learning my_string = "{1} is a good option for beginners in {0}"

print(my_string.format("Research Papers","Machine Learning")) OUTPUT:

Machine Learning is a good option for beginners in Research Papers

Keyword arguments help to call the variable in format() by calling that variable name inside the curly brackets:

my_string = "{0} is a good option for beginners in {domain}"

print(my_string.format("Research Papers",domain = "Machine Learning")) OUTPUT:

Research Papers is a good option for beginners in Machine Learning

We can use both the keyword and positional arguments together:

my_string = "{domain} is a good option for beginners in {0}"

print(my_string.format("Research Papers",domain = "Artificial Intelligence")) OUTPUT: Artificial Intelligence is a good option for beginners in Research Papers

4) Type Specification:

More parameters can be enclosed among the curly brackets of our syntax by using format code syntax. In this syntax, wherever field_name is, there it specifies the indicant of the argument or keyword to the str.format() technique, and conversion refers to the conversion code of the data type. Some conversion types are:

s — strings

d — decimal integers (base-10)

f — float

c — character

b — binary

o — octal

x — hexadecimal with lowercase letters after 9

e — exponent notation

my_string = "The Temperature in {0} today is {1:d} degrees outside!"

print(my_string.format("Research Papers",22)) OUTPUT:

The Temperature in Vizag today is 22 degrees outside!

Make sure you are using the correct conversion. You will get the below error if you are using different conversion codes :

my_string = "The Temperature in {0} today is {1:d} degrees outside!"

print(my_string.format("Vizag",22.025)) --------------------------------------------------------------------ValueError Traceback (most recent call last) in () 1 my_string = "The Temperature in {0} today is {1:d} degrees outside!" ----> 2 print(my_string.format("Vizag",22.025)) ValueError: Unknown format code 'd' for object of type 'float'

You can even limit the number of decimal points in a floating integer:

my_string = "The Temperature in {0} today is {1:f} degrees outside!"

print(my_string.format("Vizag",22.025)) OUTPUT:

The Temperature in Vizag today is 22.025000 degrees outside! my_string = "The Temperature in {0:20} today is {1:.2f} degrees outside!"

print(my_string.format("Vizag",22)) OUTPUT:

The Temperature in Vizag today is 22.02 degrees outside!

5) Spacing and Alignments using formatter:

We can use the format() to apply spaces or alignment to the right or left or both sides of placeholder. The alignment codes are:

< : left-align text

^ : center text

> : right-align

my_string = "The Temperature in {0:20} today is {1:d} degrees outside!"

print(my_string.format("Vizag",22)) OUTPUT:

The Temperature in Vizag today is 22 degrees outside! my_string = "The Temperature in {0} today is {1:20} degrees outside!"

print(my_string.format("Vizag",22)) OUTPUT:

The Temperature in Vizag today is 22 degrees outside!

We can see that strings are left-justified and numbers are right-justified. By using format() we can alter both of them as below:

my_string = "The Temperature in {0:>20} today is {1:d} degrees outside!"

print(my_string.format("Vizag",22)) OUTPUT:

The Temperature in Vizag today is 22 degrees outside! my_string = "The Temperature in {0:<20} today is {1:d} degrees outside!"

print(my_string.format("Vizag",22)) OUTPUT:

The Temperature in Vizag today is 22 degrees outside! my_string = "The Temperature in {0:^20} today is {1:d} degrees outside!"

print(my_string.format("Vizag",22)) OUTPUT:

The Temperature in Vizag today is 22 degrees outside!

6 )Organizing data:

We tend to organize data in Excel sheet where we can adjust the column size in various methods, but how can we apply the same thing in the program where the values in a column increments in an exponential way and the items in one column comes into the other or the end user may find difficult to understand which value belongs to which column.

for i in range(4,15):

print(i,i*i,i*i*i) OUTPUT: 4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

11 121 1331

12 144 1728

13 169 2197

14 196 2744

This is where we can use format() to define the space between each column so that the end user can easily differentiate between values of different columns.

for i in range(4,15):

print("{:6d} {:6d} {:6d}".format(i,i*i,i*i*i)) OUTPUT:

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

11 121 1331

12 144 1728

13 169 2197

14 196 2744

Summary:

From the above uses, we can say that formatters for variable substitution are an effective way to concatenate strings, convert values, organize values and data. Formatters represent an easy however non-descriptive manner for passing variable substitutions into a string, and are helpful for creating certain output that is decipherable and user friendly.

THANK YOU