并非在字符串格式化期间转换所有参

时间:2016-02-11 19:14:17

标签: python syntax

我正在学习Python。在做练习时,我收到了错误

  

Python TypeError:并非在字符串格式化期间转换所有参数

我已经找到了答案,但我不明白我找到的代码。

print "What's your name?",
name = raw_input()
print "What's your middle name?",
middle_name = raw_input()
print "Where do you live?",
country = raw_input()
print "Make of the car you drive?",
car = raw_input()
print "Are you single or married?",
socstatus = raw_input()
print "Are you Men or Woman?",
sex = raw_input()

print "Let me see if I understood correctly. Your complete name is %r %r, you live in %r, rides on a %r, and you are a %r $r." % (name, middle_name, country, car, socstatus, sex)

3 个答案:

答案 0 :(得分:0)

这是一个简单的语法问题:您的上一个格式规范似乎是 $ r 而不是%r。因此,您只有五种格式规范,但有六个变量。改变最后一个。

print "Let me see if I understood correctly. Your complete name is %r %r,
you live in %r, rides on a %r, and you are a %r %r." % (name, middle_name,
country, car, socstatus, sex)

答案 1 :(得分:0)

您使用$ r代替%r作为最终变量。

答案 2 :(得分:0)

格式字符串中有$r而不是%r。但是,请记住,不推荐使用%r格式样式。您应该使用当前支持位置参数的str.format()。

# Get variables...
print("Let me see if I understood correctly. Your complete name is {} {}, you live in {}, rides on a {}, and you are a {} {}.".format(name, middle_name, country, car, socstatus, sex))