学习 python Python TypeError:格式字符串参数不足[重复]

问题描述 投票:0回答:1

我是Python新手,正在尝试学习基础知识

今天刚学会如何格式化字符串,不知道这行代码有什么问题

data = ["Zac", "poor fella", 100]
format_string = "%s is a %s, his bank account has $%s."
print(format_string % data)

我的目标是尝试打印出“约翰是个穷人,他的银行账户有 100 美元。”

但是当我运行它时,它返回“Python TypeError:格式字符串的参数不足”

请告诉我我做错了什么,谢谢!

我尝试在 format_string 和 data 之间添加括号

python python-3.x string list string-formatting
1个回答
0
投票

您必须使用

%
来格式化字符串,并且您应该具有与数据列表中的元素相同数量的占位符
%s

data = ["Zac", "poor fella", 100]
print("%s is a %s, his bank account has $%s." % tuple(data))

结果: Zac 是个穷人,他的银行账户里只有 100 美元。

您可以使用现代的 f-string 格式:

data = ["Zac", "poor fella", 100]
print(f"{data[0]} is a {data[1]}, his bank account has ${data[2]}.")
© www.soinside.com 2019 - 2024. All rights reserved.