Python format Method
In Python, the format() method allows you to format data within a string and create display templates.
string.format(x1, x2, ...)
The parameters of the format function are the values that will be inserted into the corresponding placeholders within the string.
- How to format a string in Python. There are two main ways to format a string:
- Positional formatting
- Named placeholder formatting
Positional Formatting
First, you place placeholders in the string by enclosing them in curly braces.
Each placeholder is assigned a numeric or alphanumeric index to identify it.
string = "Is it better to have {0} or {1}?"
Next, you print the string using the format() method, specifying the values for the parameters within parentheses.
Each value is separated by a comma.
print(string.format("pizza", "ice cream"))
The first parameter, "pizza," is assigned to the first placeholder {0}.
The second parameter, "ice cream," is assigned to the second placeholder {1}.
Note: The numeric index of the placeholder isn’t as important as its position in the string. So, if {1} comes before {0}, it would be filled first.
The format() method constructs the string by replacing the placeholders with the provided values, and the print function outputs it to the console.
Is it better to have pizza or ice cream?
Can I repeat a placeholder in the string?
Yes, the same placeholder can be repeated multiple times within a string.
string = "Is it better to have {0} or {1}? I think you should go with {0}"
In this case, the output from the previous example would be:
Is it better to have pizza or ice cream? I think you should go with pizza.
Named Placeholder Formatting
Besides positional placeholders, you can also use named placeholders.
In this case, you use descriptive names as placeholders to uniquely identify a field within the string.
string = "It’s {hour} o’clock and {minutes}"
When displaying the string, you assign values to the placeholders using the format() method.
Here, the order in which you assign the values doesn’t matter.
print(string.format(minutes="a quarter past", hour=10))
The placeholder {minutes} is assigned the string "a quarter past".
The placeholder {hour} is assigned the integer value 10.
The format() method builds the string, and the print() function outputs it to the screen.
It’s 10 o’clock and a quarter past
And so on.
- Note: The format method also allows you to access an object’s attributes within a class.
- How to access class attributes using the format method
- How to manage placeholders in the format method
- How to create a display template with a list
- How to format dictionary data