Jun 24, 2020

format() Advanced

Format() Advanced

Hey guys, we have already discussed mostly about formatting of strings by format() method.

In this we will discuss more into format() and its use in a higher level of coding world.

Formatting class members using format()

Python internally uses getattr() for class members in the form “.age”. And, it uses __getitem__() lookup for dictionary members in the form “[index]”.

Look at the code,




Here home object is passed through a keyword p.

It accesses the name using .name and .age of the Home.

Formatting dictionary members using format()

Take a look the code below,


Try it out and you will get this output below,


Same concept of class members is used. In this it is accessed using [name] and [age].

There is an easier way of formatting dictionaries in Python.



Check out the output on your own for better understanding.

Note-  ** is a format parameter (minimum field width).

Dynamic formatting using format()


The positional argument passed here is ‘dog’ and fill, align and width are keyword arguments.


Likewise, in the second example, 27.5864 is the positional argument and, align, width and precision are passed to the template string as format codes.


Hope all your doubts regarding this are clear now.

If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".


Do subscribe to our daily blog update by clicking here.


Thank You!

 


No comments:

Post a Comment