format() Function in Python

Python format() Function

The format() function in Python is used to format strings. It allows you to insert values into a string and control how they are displayed.

The format() function can be used with string literals or variables, and it takes one or more arguments that define the values to be inserted into the string.

Here is the syntax for using the format() function:

formatted_string = "string {0} {1} ...".format(value1, value2, ...)

In the syntax, {0}, {1}, etc. are placeholders that define where the values should be inserted. The values are provided as arguments to the format() function, in the same order as the placeholders.

Here are some examples to illustrate how the format() function works:

name = "Alice"
age = 25
height = 165.5

formatted_string = "My name is {}, I am {} years old, and my height is {} cm.".format(name, age, height)
print(formatted_string)
# Output: My name is Alice, I am 25 years old, and my height is 165.5 cm.

formatted_string = "My name is {0}, I am {1} years old, and my height is {2:.2f} cm.".format(name, age, height)
print(formatted_string)
# Output: My name is Alice, I am 25 years old, and my height is 165.50 cm.

In the second example, {2:.2f} is a format specifier that specifies that the third value (height) should be formatted as a floating-point number with 2 decimal places.

The format() function also supports named placeholders, which can be useful for better readability and code maintainability. Here is an example:

name = "Alice"
age = 25

formatted_string = "My name is {name}, and I am {age} years old.".format(name=name, age=age)
print(formatted_string)
# Output: My name is Alice, and I am 25 years old.

In this example, the placeholders {name} and {age} are replaced with the values of the name and age variables, respectively, using the named arguments in the format() function.