Python: Formatting methods

Sting formatting with .format() method

A good way to format objects into the strings to print statements is with the string.format() method.

The syntax will be:

print('Hello {}, how are you doing today?'.format('Danyal'))

Let’s take a look at an other example with multiple parameters. Now what’s going to happen?

Well, strings will be inserted in order they are supplied to .format() method.

Other the other hand, if you need to place the strings in specific place, following is the example:

By using indexes this is not certain and correct team names are placed. To avoid this problem we can assign variables, take a look at example below.

Float formatting with .format() method

Let now take a look at usage of .format() for float values, let’s take a look at examples:

Float formatting follows “{value:width.precision f}”

In above example we formatted float value up to 3 decimals.

String formatting with f

Instead of using .format(), using just “f” with do the same, take a look at example below.

Author: Danyal
I'm working as programmer since 2002. Born, grew up, studied and worked in Pakistan now Im located in Denmark since 2006.