Topics covered

  • F string formating in printing text
  • Alignment, padding Fstring
  • Format dates in Printing

F string basics

person = "Richard"
print(f"The name of the boy is {person}")
The name of the boy is Richard

Using a dictionary with f string

d = {'Roll no' : 12 , 'Subject': "English"}
print(f"The student with roll no {d['Roll no']}, got highest marks in {d['Subject']}")
The student with roll no 12, got highest marks in English

Using a list

l = ["mango", "orange","banana"]
print(f"The fruit that I enjoy the most is {l[0]} and {l[1]}")
The fruit that I enjoy the most is mango and orange

Minimum Widths, Alignment and Padding

You can pass arguments inside a nested set of curly braces to set a minimum width for the field, the alignment and even padding characters.

library = [('Author', 'Topic', 'Pages'), ('Twain', 'Rafting', 601), ('Feynman', 'Physics', 95), ('Hamilton', 'Mythology', 144)]

Tuple unpacking

for author, topic, page in library:
    print(f"{author}, {topic},{page}")
Author, Topic,Pages
Twain, Rafting,601
Feynman, Physics,95
Hamilton, Mythology,144

aligning the text

for author, topic, page in library:
    print(f"{author:{10}} {topic:{8}}{page:{7}}")
Author     Topic   Pages  
Twain      Rafting     601
Feynman    Physics      95
Hamilton   Mythology    144

Here the first three lines align, except Pages follows a default left-alignment while numbers are right-aligned. Also, the fourth line's page number is pushed to the right as Mythology exceeds the minimum field width of 8. When setting minimum field widths make sure to take the longest item into account.

To set the alignment, use the character < for left-align, ^ for center, > for right.
To set padding, precede the alignment character with the padding character (- and . are common choices).

for author, topic, page in library:
    print(f"{author:{10}} {topic:{10}}{page:>{7}}")
Author     Topic       Pages
Twain      Rafting       601
Feynman    Physics        95
Hamilton   Mythology     144
for author, topic, page in library:
    print(f"{author:{10}} {topic:{10}}{page:.>{7}}")
Author     Topic     ..Pages
Twain      Rafting   ....601
Feynman    Physics   .....95
Hamilton   Mythology ....144
 
from datetime import datetime
today = datetime(year=2022, month =1, day = 27)
print(f'{today:%B,%d, %Y}')
January,27, 2018