The format()
function in Python is a string method that allows you to format a string by replacing placeholders with values. You can insert variables or expressions within curly braces {} in the string, which are then replaced by the corresponding values passed as arguments to the format() function.
Parameter Values
Parameter | Description |
---|---|
args | A list of replacements. |
Return Values
format()
from String Methods can return a formatted string
type.
How to Use format()
in Python
Example 1:
The format()
method formats the specified value(s) and inserts them inside the string's placeholder {}.
print('The {0} {1} jumps over the {2}'.format('quick', 'brown', 'fox'))
Example 2:
You can pass variables as arguments to the format()
method.
adjective = 'tall'
noun = 'building'
print('The {0} {1} towers over the city'.format(adjective, noun))
Example 3:
The format()
method allows for formatting the inserted values, such as specifying the number of decimal places for floats.
num = 3.14159
print('The value of pi is {0:.2f}'.format(num))