Print Function
The format method controls the layout of output. You write a template string containing placeholders in braces, such as {}, then call .format() on it and give it the values, separated by commas. Placeholders are filled in order: the first pair of braces takes the first value, the second pair the second, and so on.
Text outside a placeholder is printed exactly as it stands, which is what makes a template useful: a label in front of a value, or a unit straight after it, is written once instead of being rebuilt on every run. In "Time: {:.2f} minutes" only the number changes.
Inside a placeholder, a colon introduces the format specification. The first number sets the width of the field in columns, a full stop and a digit give the number of decimal places, and the letter f at the end shows the value as a fixed-point real number. The order is width, full stop, decimal places, letter, so {:7.2f} means seven columns wide with two decimal places.
An alignment character goes before the width: < left-aligns, > right-aligns and ^ centres. A value shorter than the stated width is padded with spaces until the field is full, so a column of numbers lines up under its heading. With {:<8}{:>6.1f} a five-letter name gains three trailing spaces, and 8.5 is shown as three spaces then 8.5, keeping the decimal points in one column.
Formatted strings, or f-strings, are an alternative accepted way of inserting values and expressions into a line of output text. You put the letter f immediately before the opening quotation mark and the variable or expression straight inside the braces, so the format method is never called. A format specification still follows a colon inside the braces, so both styles can give identical layouts.
Formatting builds a new piece of text for display only, so the number stored in the variable keeps its full precision for later calculations.
Edexcel GCSE Computer Science · Print Function