Python格式化字符串报错TypeError: not enough arguments for format string求解决
问题分析与解决
- 错误根源:
%格式化语法中,当右侧是列表这类序列时,直接使用format_string % data会把整个列表视为单个参数,但你的格式化字符串有3个%s占位符,需要3个独立参数,参数数量不匹配导致TypeError。 - 两种修正方式:
- 用
*解包列表,将列表元素逐个传入:data = ["John", "poor fella", 100] format_string = "%s is a %s, his bank account has $%s." print(format_string % (*data,)) - 将列表改为元组(元组可直接被
%正确识别为多参数):data = ("John", "poor fella", 100) format_string = "%s is a %s, his bank account has $%s." print(format_string % data)
- 用
- 注意:要得到目标输出「John is a poor fella, his bank account has $100.」,需把原代码中的
Zac替换为John。
内容的提问来源于stack exchange,提问作者Zack
相关产品推荐
相关产品推荐

