Python 类型错误:使用 %s 时没有足够的格式字符串参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24252358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:19:01  来源:igfitidea点击:

TypeError: not enough arguments for format string when using %s

pythonstringstring-formattingtypeerror

提问by beepbeep

this is my code

这是我的代码

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)

I've searched the topic but I don't understand.

我已经搜索了该主题,但我不明白。

采纳答案by beepbeep

You need to put your arguments for string formatting in parenthesis:

您需要将字符串格式的参数放在括号中:

print (... % (name, last_name, gender, age))

Otherwise, Python will only see nameas an argument for string formatting and the rest as arguments for the printfunction.

否则,Python 只会将其name视为字符串格式的参数,而将其余部分视为函数的参数print



Note however that using %for string formatting operations is frowned upon these days. The modern approach is to use str.format:

但是请注意,%这些天不赞成使用字符串格式化操作。现代方法是使用str.format

print ("So your name is {}, your last name is {}, you are {} and you are {} years old".format(name, last_name, gender, age))

回答by arshajii

You need a set of parenthesis:

你需要一组括号:

>>> '%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'is evaluated as ('%s %s' % 'a'), 'b', which produces an error in '%s %s' % 'a'since you have fewer arguments than format specifiers.

'%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))