Format Function in Python (str.format()) is technique of the string category permits you to try and do variable substitutions and data formatting. It enables you to concatenate parts of a string at desired intervals through point data format. This article will guide you through a number of the common uses of formatters in Python, which will help your code and program to be user-friendly.
Here are all the pointers that are discussed over here:
To get in-depth knowledge on any trending technologies along with its various applications, you can enroll for live Edureka’s Python training with 24/7 support and lifetime access.
1) Single Formatter:
Formatters work by fixing one or a lot of replacement fields or placeholders outlined by a pair of curly brackets “{}” — into a string and calling the str.format() technique. You’ll need to 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 the moment you run the program. Single formatters can be defined as those where there is only one placeholder. In the example below, you will be able to see the implementation of the format in the print statement.
Apart from directly using in the print statement, we can also use format() to a variable:
EXAMPLE:
print("{} is a good option for beginners in python".format("Edureka"))
Output: Edureka is a good option for beginners in python
Apart from directly using 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("Edureka"))
OUTPUT: Edureka 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 another set of curly brackets where we want substitution and passing a second value into format(). Python will then replace the placeholders by values that are passed as the parameters.
EXAMPLE:
my_string = "{} is a good option for beginners in {}" print(my_string.format("Edureka","Machine Learning"))
Output: Edureka is a good option for beginners in Machine Learning
You can add any number of placeholders or curly brackets that you 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("Edureka","excellent","experienced","Machine Learning"))
Output: Edureka is an excellent option for experienced in Machine Learning
So moving ahead with Format Function in Python
3) Formatters using Positional and Keywords Arguments:
When placeholders are empty {}, the 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 is 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:
EXAMPLE:
my_string = "{0} is a good option for beginners in {1}" print(my_string.format("Edureka","Machine Learning"))
Output: Edureka is a good option for beginners in Machine Learning
Keyword arguments help to call the variable in format() by calling that variable name inside the curly brackets:
EXAMPLE:
my_string = "{0} is a good option for beginners in {domain}" print(my_string.format("Edureka",domain = "Machine Learning"))
Output: Edureka is a good option for beginners in Machine Learning
We can use both the keyword and positional arguments together:
EXAMPLE:
my_string = "{domain} is a good option for beginners in {0}" print(my_string.format("Edureka",domain = "Artificial Intelligence"))
my_string = “{domain} is a good option for beginners in {0}”
print(my_string.format(“Edureka”,domain = “Artificial Intelligence”))
Artificial Intelligence is a good option for beginners in Edureka
4) Type Specification:
More parameters are 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
EXAMPLE:
my_string = "The Temperature in {0} today is {1:d} degrees outside!" print(my_string.format("Vizag",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 :
EXAMPLE:
my_string = "The Temperature in {0} today is {1:d} degrees outside!" print(my_string.format("Vizag",22.025))
Output:
—————————————————————————
ValueError Traceback (most recent call last)
<ipython-input-12-4ce31dc07a23> in <module>
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:.2f} degrees outside!" print(my_string.format("Vizag",22.025))
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 the placeholder. The alignment codes are:
< : left-align text
^ : center text
> : right-align
EXAMPLE:
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!
EXAMPLE:
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 thems 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!
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.
EXAMPLE:
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 the values of different columns.
EXAMPLE:
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
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. Join our course on Master Python programming today to become an expert.
Discover how to create mobile apps that look and feel great on any platform with a comprehensive Flutter Course.
This brings us to the end of this article on Format Function in Python. I hope you are clear with all that has been shared with you. Make sure you practice as much as possible and revert your experience.
Got a question for us? Please mention it in the comments section of this “Format Function in Python” blog and we will get back to you as soon as possible.