0
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' ??

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

thanks! but hmmmm... so I put print(mystring %s (food1, food2)) then it says the same :(
@Anny I was referring to the %s in 'Fred enters the swamp and picks up %s to eat later.' See further update in the question
got it! so I put mystring= 'Fred enters the swamp and picks up a %s and a %s to eat later.' :]
0

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

4 Comments

yay! it works! now Fred gets to eat a python and a swamp apple! but I still don't understand why the command print(mystring % (food1, food2)) says type error? basically I put on the same thing as from the book but it didn't give the same output
Its beacuse you are passing two strings while there is only one %s in mystring. What I've done is added both strings food1 and food2 together with an and between them, so now there is only one string.
got it! thanks a lot! i just found out i put the wrong variable:P it should be mystring= 'Fred enters the swamp and picks up a %s and a %s to eat later.'
Yeah! I was gonna change your mystring, but was kinda afraid. :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.