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 a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.