Python string Method - format()
The format()
method in Python strings is used to format a string by replacing placeholders in the string with corresponding values. The placeholders are marked by curly braces {}
and can contain optional format specifiers.
The syntax for the format()
method is as follows:
string.format(value1, value2, ...)
Here, string
is the string that we want to format, and value1
, value2
, etc. are the values that we want to substitute for the placeholders in the string.
Example:
# Defining a string with placeholders my_string = "My name is {} and I am {} years old" # Using the format() method to replace the placeholders result = my_string.format("Alice", 30) print(result) # Output: "My name is Alice and I am 30 years old"
In the above example, the format()
method is used to replace the two placeholders {}
in the string "My name is {} and I am {} years old"
with the values "Alice"
and 30
, respectively. The resulting string "My name is Alice and I am 30 years old"
is then assigned to the variable result
. The output of the program is "My name is Alice and I am 30 years old"
.
We can also use named placeholders in the string by providing names inside the curly braces. Example:
# Defining a string with named placeholders my_string = "My name is {name} and I am {age} years old" # Using the format() method to replace the named placeholders result = my_string.format(name="Bob", age=25) print(result) # Output: "My name is Bob and I am 25 years old"
In this example, the placeholders in the string "My name is {name} and I am {age} years old"
are named "name"
and "age"
. The format()
method is used to replace these named placeholders with the values "Bob"
and 25
, respectively. The resulting string "My name is Bob and I am 25 years old"
is then assigned to the variable result
. The output of the program is "My name is Bob and I am 25 years old"
.
We can also use format specifiers to control the formatting of the substituted values. For example, we can use the format specifier :.2f
to format a floating-point number with two decimal places. Example:
# Defining a string with a formatted value my_string = "The value of pi is approximately {:.2f}" # Using the format() method to replace the formatted value result = my_string.format(3.141592653589793) print(result) # Output: "The value of pi is approximately 3.14"
In this example, the placeholder {:.2f}
in the string "The value of pi is approximately {:.2f}"
specifies that the substituted value should be formatted as a floating-point number with two decimal places. The format()
method is used to replace this placeholder with the value 3.141592653589793
, which is then formatted as "3.14"
. The resulting string "The value of pi is approximately 3.14"
is then assigned to the variable result
. The output of the program is "The value of pi is approximately 3.14"
.