快速了解Python中format函数的使用
我们非常重视原创文章,为尊重知识产权并避免潜在的版权问题,我们在此提供文章的摘要供您初步了解。如果您想要查阅更为详尽的内容,访问作者的公众号页面获取完整文章。
Python format() Function Overview
The format()
function in Python is a built-in function used for string formatting. It allows the insertion of specified values into a string by replacing placeholders represented by {}
. The function follows the syntax:
str.format(*args, **kwargs)
*args and **kwargs are optional parameters representing one or more values to insert and one or more key-value pairs, respectively.
Examples of format() Function Usage
No Parameters
s = "Hello, {}!" print(s.format("world")) # Output: Hello, world!
Positional Arguments
s = "I am {} years old and my name is {}." print(s.format(25, "John")) # Output: I am 25 years old and my name is John.
Keyword Arguments
s = "My name is {name} and I am {age} years old." print(s.format(name="John", age=25)) # Output: My name is John and I am 25 years old.
Mixing Positional and Keyword Arguments
s = "My name is {name} and I am {0} years old." print(s.format(25, name="John")) # Output: My name is John and I am 25 years old.
Using Dictionaries as Keyword Arguments
person = {"name": "John", "age": 25} s = "My name is {name} and I am {age} years old." print(s.format(**person)) # Output: My name is John and I am 25 years old.
Using Indexes
s = "The {2} of {0} is {1:.2f}" print(s.format("pi", 3.14159, "circle")) # Output: The circle of pi is 3.14
Additional Examples
print(format(2918)) print(format(0x500, 'X')) print(format(3.14, '0=10')) print(format(3.14159, '05.3')) print(format(3.14159, 'E')) print(format('test', '20')) print(format('test', '^20'))
2918
500
00000003.14
03.14
3.141590E+00
test
test
Conclusion
The format()
function is essential for conveniently inserting various values into strings, enriching and adding flexibility to string content in Python.
想要了解更多内容?