python - Python 中的 format() 实际上是做什么的?
问题描述
在使用了 Ruby、R 和一些 Java 之后,我开始接触 Python3。我立即遇到了 format() 函数,我对它的作用有点迷茫。我读过Python | format() 函数,并看到它在某种程度上类似于 ruby:
my_name = "Melanie"
puts "My name is #{my_name}."
输出:“我的名字是梅兰妮。”
但是,我不明白为什么我不能只使用上面的变量。我一定非常误解了 format() 函数的用法。(我是新手,请温柔。)
那么 format() 实际上是做什么的呢?
解决方案
您绝对可以通过以下方式在显示的字符串示例中使用变量:
my_name = "Melanie"
Output = "My name is " + my_name + "."
print(Output)
My name is Melanie.
这是最简单的方法,但不是最优雅的。
在上面的示例中,我使用了 3 行并创建了 2 个变量(my_name 和 Output)
但是,我可以使用 format() 仅使用一行代码而不创建任何变量来获得相同的输出
print("My name is {}.".format("Melanie"))
My name is Melanie.
花括号 {} 用作占位符,我们希望放入占位符的值作为参数传递给格式函数。
如果字符串中有多个占位符,python 将按顺序将占位符替换为值。
只需确保作为参数传递给 format() 的值的数量等于在字符串中创建的占位符的数量。
例如:
print("My name is {}, and I am {}.".format("Melanie",26))
My name is Melanie, and I am 26.
有 3 种不同的方式来指定占位符及其值:
类型 1:
print("My name is {name}, and I am {age}.".format(name="Melanie", age=26))
类型 2:
print("My name is {0}, and I am {1}.".format("Melanie",26))
类型 3:
print("My name is {}, and I am {}.".format("Melanie",26))
此外,通过使用 format() 而不是变量,您可以:
- 指定数据类型,并且
- 添加格式化类型以格式化结果。
例如:
print("{0:^7} has completed {1:.3f} percent of task {2}".format("Melanie",75.765367,1))
Melanie has completed 75.765 percent of task 1.
我已将百分比字段的数据类型设置为浮点数,有 3 个小数,名称的字符长度为 7,并使其居中对齐。
对齐代码是:
' < ' : 左对齐文本
' ^ ' : 居中文本
' > ' : 右对齐
当您对字符串执行多个替换和格式化时,format() 方法很有帮助。
推荐阅读
- python - 如何基于 pandas 表构建稀疏矩阵?
- django-models - 如何在模板 wagtail 中访问默认页面模型
- python - 如何在系统关闭时运行 Python 脚本(Windows 7)
- javascript - Wordpress acf 尝试使用 acf 中继器字段隐藏和显示列表中的 div
- mysql - 未加载 QMYSQL 驱动程序。用记事本写的;文件.py
- jquery - 从国家下拉列表中选择美国时的美国电话号码验证
- memory - 我们可以在 gem5 模拟器上运行 memtestx86 吗?
- r - 使用 R 代码实现 Web 自动化
- apache-spark - Spark XML API - 标签之间的文本
- javascript - 为什么我的道具带回的是动作功能,而不是日期?