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

                person = {'name': 'John', 'age': 23}

sentence = 'My name is ' + person['name'] + ' and I am ' + str(person['age']) + ' years old.'
print(sentence)
Output- 
My name is John and I am 23 years old.
            

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.

                sentence = 'My name is {} and I am {} years old.'.format(person['name'], person['age'])
print(sentence)
Output- 
My name is John and I am 23 years old.
            

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.

                sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age'])
print(sentence)
            

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.

                tag = 'h1'
text = 'This is a headline'

sentence = '<{0}>{1}</{0}>'.format(tag, text)
print(sentence)
Output- 
<h1>This is a headline</h1>
            

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().

                sentence = 'My name is {0[name]} and I am {0[age]} years old.'.format(person)
print(sentence)
Output- 
My name is John and I am 23 years old.
            

Also we can access class object using the same way.

                class Person():

    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person('Jack', '33')

sentence = 'My name is {0.name} and I am {0.age} years old.'.format(p1)
print(sentence)
Output- 
My name is Jack and I am 33 years old.
            

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

                sentence = 'My name is {name} and I am {age} years old.'.format(**person)
print(sentence)
Output- 
My name is John and I am 23 years old.
            

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

                for i in range(1, 11):
    sentence = 'The value is {:02}'.format(i)
    print(sentence)
Output-

The value is 01
The value is 02
The value is 03
The value is 04
The value is 05
The value is 06
The value is 07
The value is 08
The value is 09
The value is 10
            

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

                pi = 3.14159265

sentence = 'Pi is equal to {:.2f}'.format(pi)

print(sentence)
Output- 
Pi is equal to 3.14
            

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

                import datetime

my_date = datetime.datetime(2016, 9, 24, 12, 30, 45)

#September 24, 2016

sentence = '{:%B %d, %Y}'.format(my_date)

print(sentence)
Output- 
September 24, 2016
            

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
12

Influence

278

Total Hits

1

Posts