1.1 Learning to use F string literal
Learning to use F string for printing. Also alignment and padding of Fstring. Formating of dates while using Fstring is also shown.
Topics covered
- F string formating in printing text
- Alignment, padding Fstring
- Format dates in Printing
person = "Richard"
print(f"The name of the boy is {person}")
d = {'Roll no' : 12 , 'Subject': "English"}
print(f"The student with roll no {d['Roll no']}, got highest marks in {d['Subject']}")
l = ["mango", "orange","banana"]
print(f"The fruit that I enjoy the most is {l[0]} and {l[1]}")
library = [('Author', 'Topic', 'Pages'), ('Twain', 'Rafting', 601), ('Feynman', 'Physics', 95), ('Hamilton', 'Mythology', 144)]
for author, topic, page in library:
print(f"{author}, {topic},{page}")
for author, topic, page in library:
print(f"{author:{10}} {topic:{8}}{page:{7}}")
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}}")
for author, topic, page in library:
print(f"{author:{10}} {topic:{10}}{page:.>{7}}")
from datetime import datetime
today = datetime(year=2022, month =1, day = 27)
print(f'{today:%B,%d, %Y}')