What is the usage of the format function in Python3?
In Python3, the format() function is a method used for formatting strings. It allows you to insert the values of variables, constants, or expressions at specific positions within the string.
There are two forms of using the format() function.
- Positional parameters format:
- String.format(value)
- This format uses curly braces {} to identify the position where values should be inserted, and then the values are inserted into the corresponding positions by the arguments of the format() function.
- Keyword arguments format:
- “String {keyword}”.format(keyword=value)
- This format uses placeholders {keywords} to indicate the position where values are to be inserted, and then inserts the values into the corresponding positions using keyword arguments in the format() function.
Here are some examples:
name = "Alice"
age = 25
# 位置参数形式
print("My name is {}, and I am {} years old.".format(name, age))
# 关键字参数形式
print("My name is {name}, and I am {age} years old.".format(name=name, age=age))
Output:
My name is Alice, and I am 25 years old.
My name is Alice, and I am 25 years old.
In addition to using positional and keyword arguments, the format() function also supports other formatting options such as specifying precision for numbers, fill characters, and alignment. For more detailed formatting options, refer to the string formatting section in the Python official documentation.