The format()
function is a built-in function in Python used for string formatting. It takes the template string and values to be substituted into the placeholders within the string. The placeholders in the template string are specified using curly braces {}. The format()
function then replaces these placeholders with the corresponding values provided as arguments to the function. This function allows for flexible formatting of strings using various parameters such as alignment, padding, precision, and data type specification.
Parameter Values
Parameter | Description |
---|---|
value | A value to be inserted into the formatted string. |
format_spec | A string containing a format specifier that identifies how the value should be formatted. |
Return Values
The format()
function in Python returns a formatted string using a specified format.
How to Use format()
in Python
The format()
method formats the specified value(s) and inserts them into the string where the placeholders are.
name = 'Alice'
age = 30
message = 'Hello, my name is {} and I am {} years old'.format(name, age)
print(message)
You can also use indexing inside the placeholders with {0}
, {1}
, etc.
price = 19.95
discount = 0.1
final_price = 'The final price is ${0:.2f} after a {1:.0%} discount'.format(price, discount)
print(final_price)
It supports named placeholders by providing key-value pairs in format()
.
data = {'name': 'Bob', 'age': 25}
message = 'My name is {name} and I am {age} years old'.format(**data)
print(message)