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 skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting