A format specifier controls how an interpolated value appears in an f-string. It follows a colon inside the braces, such as f"{value:^10}" for centered, width-limited output. section 2.1.4
Use common specifiers to shape readable text and numeric output:
- <, >, and ^ select left, right, and center alignment; an optional character supplies padding. section 2.1.4
- :,d, :b, :o, and :x represent integers in decimal, binary, octal, and hexadecimal forms. section 2.1.4
- .2f limits a float to two decimal places, while :e and :% select scientific and percentage notation. section 2.1.4
Align task records
task_ids = [1, 2, 3] task_names = ['Do homework', 'Laundry', 'Pay bills'] task_urgencies = [5, 3, 4] for i in range(3): print(f'{task_ids[i]:^12}{task_names[i]:^12}{task_urgencies[i]:^12}') # 1 Do homework 5 # 2 Laundry 3 # 3 Pay bills 4 A reusable function can accept a format string such as '^15' or '^18', avoiding repeated formatting code. section 2.1.4
Format temperature input
temperature = float(input()) if temperature < 10: message = "It's cold!" elif temperature <= 25: message = "It's cool!" else: message = "It's hot!" print(f"You entered {temperature:.1f} degrees. {message}") A value such as 15.75 is displayed as 15.8. section 2.2.5
Listing 2.2 Applying format specifiers in f-strings
task_ids = [1, 2, 3]
task_names = ['Do homework', 'Laundry', 'Pay bills']
task_urgencies = [5, 3, 4]
for i in range(3):
print(f'{task_ids[i]:^12}{task_names[i]:^12}{task_urgencies[i]:^12}') #1
# Output the following lines:
1 Do homework 5
2 Laundry 3
3 Pay bills 4
Shows aligned identifiers, names, and urgency values in a complete f-string listing with representative output. section 2.1.4




