Format in Python
Overview
The format method in Python is a versatile string method that allows for string formatting by embedding placeholders within a string and replacing them with specified values. This method was widely used before the introduction of f-strings, which offer a more concise and readable way to format strings.
String Formatting Techniques
Before the advent of f-strings, Python developers primarily used two methods for string formatting: the C-style % formatting and the format method. Below is a code snippet illustrating both approaches:
task1 = "Name: %s; Urgency Level: %d" % (name, urgency) #1
task2 = "Name: {}; Urgency Level: {}".format(name, urgency)
#1 The % sign separates the string literal and the tuple object.
C-Style % Formatting
In the C-style approach, the % sign within the string literal indicates where a variable will be formatted. The variables are then provided as a tuple following the % sign.
format Method
The format method uses curly braces {} as placeholders within the string. The corresponding variables are listed in the format method, which replaces the placeholders with the specified values.
F-Strings and Format Specifiers
With the introduction of f-strings, Python provided a more efficient and readable way to format strings. F-strings allow for embedding expressions inside string literals, using curly braces {}. They also support format specifiers, which are optional components that define how the interpolated string should be formatted.
Components of an F-String
Figure 2.2 Components of an f-string. The expression is the first part and is required. The expression is evaluated first, and a corresponding string is created. The second part, which is the format specifier, is optional.
Text Alignment with Format Specifiers
Format specifiers in f-strings can be used to align text, pad strings, and more. The syntax f"{expr:x<n}" is used, where expr is the expression to be formatted, x is the padding character (defaulting to spaces if omitted), < indicates left alignment, and n specifies the width.
Here is an example of using format specifiers for text alignment:
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:](https://livebook.manning.com/book/python-how-to/chapter-2/52)
1 Do homework 5
2 Laundry 3
3 Pay bills 4
#1 Applies format specifiers to the expressions
Refactoring with Format Specifiers
To avoid repetition and adhere to the DRY (Don't Repeat Yourself) principle, you can refactor code to use a variable for the format specifier. This approach allows for easy updates and experimentation with different format specifiers:
def create_formatted_records(fmt):
for i in range(3):
task_id = task_ids[i]
name = task_names[i]
urgency = task_urgencies[i]
print(f'{task_id:{fmt}}{name:{fmt}}{urgency:{fmt}}')
In this refactored function, the format specifier fmt is passed as a parameter, allowing for flexible formatting of the output.
FAQ (Frequently asked questions)
What is the format method in Python used for?
How was string formatting done in Python before f-strings?