Join us

String Formatting — Advanced Options for List, Dict, Number and Dates

Here is the example of Printing values from Dictionary without using formatting provided by Python

Here is the example of Printing values from Dictionary without using formatting provided by Python

In this example we need to pass String with exact spaces also if we are using Integer value than need to convert the same to the Integer, because of that its become complex and not much readable. so below is the solution for that.

The string format() method formats the given string into a nicer output in Python.

format() method takes any number of parameters. But, is divided into two types of parameters:

  • Positional parameters — list of parameters that can be accessed with index of parameter inside curly braces {index}
  • Keyword parameters — list of parameters of type key=value, that can be accessed with key of parameter inside curly braces {key}

We will cover all the patterns in the below examples.

In above example, we are passing index values to the String, so it will take person[‘name’] instead of 0 index and person[‘age’] in the place of 1.

Same indexing we can use when we want to repeat the value in the particular string, below is the example.

Here we are using ‘h1’ string twice, so we have repeated index 0 twice in the String.

In the below example, instead of passing dictionary parameter multiple time inside format, we can pass with index and only dictionary name need to pass under format().

Also we can access class object using the same way.

Also we use dictionary unpack to access element using format().

In the below example , we are formatting the number and added {:02 } in the format(), so it will print 2 digit numbers.

in the next example, we are formatting float value and added{:.2f} that will restrict number value till two decimal place only.

In the next example , we are formatting datetime, below is the link for the Directive used to format() datetime.

datetime - Basic date and time types - Python 3.10.5 documentation

Here ‘%B’ represents Month as locale’s full name.

%d represents Day of the month as a zero-padded decimal number.

%Y represents Year with century as a decimal number.

Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

User Popularity



Total Hits