示例代码的输出有问题

时间:2014-10-26 06:29:57

标签: python-3.x

mystring= 'Fred enters the swamp and picks up %s to eat later.'
food1= 'python'
food2 = 'swamp apples'
print(mystring % (food1, food2))
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    print(mystring % (food1, food2))
TypeError: not all arguments converted during string formatting

命令'print(mystring%(food1,food2))'我不明白为什么它会说TypeError?难道它不应该打印为'弗雷德进入沼泽地并捡起蟒蛇和沼泽苹果以后再吃'??

2 个答案:

答案 0 :(得分:1)

因为字符串中只有一个%s,而您正在尝试在

中分配两个值
print(mystring % (food1, food2))

将其更改为:

print(mystring % food1)

它打印得很好

答案 1 :(得分:0)

以这种方式使用:

mystring= 'Fred enters the swamp and picks up %s to eat later.'
food1= 'python'
food2 = 'swamp apples'
print(mystring % (food1 + ' and ' + food2))

输出:

Fred enters the swamp and picks up python and swamp apples to eat later.

Demo