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?难道它不应该打印为'弗雷德进入沼泽地并捡起蟒蛇和沼泽苹果以后再吃'??
答案 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.