Anny
Anny

Reputation: 11

something wrong with the output of sample code

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

command 'print(mystring % (food1, food2))' I don't understand why it says TypeError? Isn't it supposed to print as 'Fred enters the swamp and picks up a python and a swamp apple to eat later' ??

Upvotes: 0

Views: 49

Answers (2)

Nir Alfasi
Nir Alfasi

Reputation: 53525

Because you have only one %s in the string and you're trying to assign two values in

print(mystring % (food1, food2))

change it to:

print(mystring % food1)

and it'll print just fine

Upvotes: 1

Weafs.py
Weafs.py

Reputation: 22992

Use it this way:

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

Output:

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

Demo

Upvotes: 0

Related Questions