format() method is used to insert values into a string using placeholders ({}). It helps create dynamic and readable output by replacing placeholders with the provided values. The method returns a new formatted string without modifying the original string.
Example: In this example, values are inserted into a string using placeholders.
name = "Emma"
age = 25
msg = "My name is {} and I am {} years old.".format(name, age)
print(msg)
Output
My name is Emma and I am 25 years old.
Explanation:
- {} are placeholders inside the string.
- format(name, age) replaces the first placeholder with name and the second placeholder with age.
- The method returns a new formatted string.
Syntax
string.format(value1, value2, ...)
- Parameter: value1, value2, ... - Values to insert into the placeholders ({}).
- Return Value: Returns a new string with the placeholders replaced by the provided values.
Examples
Example 1: In this example, multiple values are inserted into a string using placeholders. This is one of the most common uses of the format() method.
name = "Harry"
age = 25
print("{} is {} years old.".format(name, age))
Output
Harry is 25 years old.
Explanation: {} placeholders are replaced by the values passed to format(). Values are inserted in the same order they are provided.
Example 2: Named placeholders make formatted strings easier to read, especially when working with multiple values.
msg = "{name} works as a {role}."
print(msg.format(name="David", role="Developer"))
Output
David works as a Developer.
Explanation: {name} and {role} are named placeholders, format() replaces them using the corresponding keyword arguments.
Example 3: The format() method can also control how numbers are displayed, such as limiting decimal places.
score = 87.4567
print("Score: {:.2f}".format(score))
Output
Score: 87.46
Explanation: :.2f formats the number as a floating-point value with two decimal places. The value is rounded automatically when necessary.