问题
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.
回答1:
You need to put your arguments for string formatting in parenthesis:
print (... % (name, last_name, gender, age))
Otherwise, Python will only see name
as an argument for string formatting and the rest as arguments for the print
function.
Note however that using %
for string formatting operations is frowned upon these days. The modern approach is to use str.format:
print ("So your name is {}, your last name is {}, you are {} and you are {} years old".format(name, last_name, gender, age))
回答2:
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.
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))
来源:https://stackoverflow.com/questions/24252358/typeerror-not-enough-arguments-for-format-string-when-using-s