如何比较 Python 字符串格式:% 与 .format?
pythonserver side programmingprogramming更新于 2025/7/4 0:12:17
% 可以接受变量或元组。因此,您必须非常明确地说明您希望它做什么。例如,如果您尝试格式化为 −
示例
my_tuple = (1, 2, 3) "My tuple: %s" % my_tuple You'd expect it to give the output: My tuple: (1, 2, 3)
输出
但它会抛出 TypeError。为了保证它总是打印,您需要将其作为单个参数元组提供,如下所示 −
"hi there %s" % (name,) # 将单个参数作为单项元组提供
每次都记住这些警告并不容易,可能会导致错误。.format 没有这些问题。相比之下,format 看起来也非常干净。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

