【问题标题】:TypeError: not enough arguments for format string when using %sTypeError: 使用 %s 时格式字符串的参数不足
【发布时间】:2014-08-06 18:57:14
【问题描述】:
这是我的代码
import sys
name = input("Enter your name:")
last_name = input("Enter your last name:")
gender = input("Enter your gender:")
age = input("Enter your age:")
print ("So your name is %s, your last name is %s, you are %s and you are %s years old" % name, last_name, gender, age)
我已经搜索过该主题但我不明白。
【问题讨论】:
标签:
python
string
string-formatting
typeerror
【解决方案1】:
您需要将字符串格式的参数放在括号中:
print (... % (name, last_name, gender, age))
否则,Python 只会将 name 视为字符串格式化的参数,其余的将视为 print 函数的参数。
但请注意,如今使用% 进行字符串格式化操作已不受欢迎。现代方法是使用str.format:
print ("So your name is {}, your last name is {}, you are {} and you are {} years old".format(name, last_name, gender, age))
【讨论】:
-
这是一个不错的选择,抛开 Python 中旧的字符串格式方法,使用这种方法:)。它避免了很多麻烦,并且在更好地格式化输出时为您提供了更大的灵活性,例如,放置空格以形成数据列。这是官方文档,里面有很多例子:) -> pyformat.info
【解决方案2】:
你需要一组括号:
>>> '%s %s' % 'a', 'b' # what you have
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>>
>>>
>>> '%s %s' % ('a', 'b') # correct solution
'a b'
'%s %s' % 'a', 'b' 被评估为 ('%s %s' % 'a'), 'b',这会在 '%s %s' % 'a' 中产生错误,因为您的参数少于格式说明符。
print("So your name is %s, your last name is %s, you are %s and you are %s years old" % (name, last_name, gender, age))