Python built-in Method - format()

h‮w//:sptt‬ww.theitroad.com

The format() method is a built-in function in Python that allows you to format a string by replacing placeholders with values. It is a powerful method for string formatting and is commonly used for creating formatted output.

Here is the syntax for format() method:

formatted_string = "my name is {}, and I am {} years old".format(name, age)

where {} is a placeholder that will be replaced with the values of name and age passed as arguments to the format() method.

Here are some examples of how to use format():

# format using positional arguments
formatted_string = "my name is {}, and I am {} years old".format("Alice", 25)
print(formatted_string)  # my name is Alice, and I am 25 years old

# format using keyword arguments
formatted_string = "my name is {name}, and I am {age} years old".format(name="Bob", age=30)
print(formatted_string)  # my name is Bob, and I am 30 years old

# format using a mix of positional and keyword arguments
formatted_string = "my name is {0}, and I am {age} years old".format("Charlie", age=35)
print(formatted_string)  # my name is Charlie, and I am 35 years old

# format using format specifiers
formatted_string = "the value of pi is approximately {:.2f}".format(3.14159)
print(formatted_string)  # the value of pi is approximately 3.14

In the first example, we use positional arguments to format the string. In the second example, we use keyword arguments. In the third example, we use a mix of positional and keyword arguments. In the fourth example, we use a format specifier to round the value of pi to two decimal places.

Note that you can also use the newer f-strings feature in Python 3.6 and above to format strings. F-strings are a more concise way to format strings than the format() method. Here is an example of how to use f-strings:

name = "Alice"
age = 25
formatted_string = f"my name is {name}, and I am {age} years old"
print(formatted_string)  # my name is Alice, and I am 25 years old

This produces the same output as the first example, but with less typing.