快速了解Python中format函数的使用

发布于 2024-10-26
941

我们非常重视原创文章,为尊重知识产权并避免潜在的版权问题,我们在此提供文章的摘要供您初步了解。如果您想要查阅更为详尽的内容,访问作者的公众号页面获取完整文章。

扫码阅读
手机扫码阅读
Python format() Function Summary

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.

Python学习杂记

探索运筹优化、机器学习、AI 和数据可视化的奥秘及其落地应用

280 篇文章
浏览 374.4K

还在用多套工具管项目?

一个平台搞定产品、项目、质量与效能,告别整合之苦,实现全流程闭环。

加入社区微信群
与行业大咖零距离交流学习
PMO实践白皮书
白皮书上线