how does the % work?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Mar 23 03:38:23 EDT 2013


On Fri, 22 Mar 2013 21:29:48 -0700, Tim Roberts wrote:

> leonardo selmi <l.selmi at icloud.com> wrote:
>>
>>i wrote this example :
>>
>>name = raw_input("What is your name?") 
>>quest = raw_input("What is your quest?") 
>>color = raw_input("What is your favorite color?")
>>
>>print """Ah, so your name is %s, your quest is %s, and your favorite
>>color is %s."""  % (name, quest, color)
> 
> No, you didn't.  You wrote:
> 
> print('''Ah, so your name is %s, your quest is %s, and your
>     favorite color is %s.''') % (name, quest, color)


The difference between those two statements may not be entirely clear to 
someone not experienced in reading code carefully.

Consider the difference between:

  print(a % b)

  print(a) % b

In the first example, the round brackets group the "a % b", which is 
calculated first, then printed.

In the second example, in Python 3, the "print(a)" is called first, which 
returns None, and then "None % b" is calculated, which raises an 
exception.

Just to add confusion, the two lines are exactly the same in Python 2, 
where Print is not a function! 


> You are using Python 3.  In Python 3, "print" is a function that returns
> None.  So, the error is exactly correct.  To fix it, you need to have
> the % operator operate on the string, not on the result of the "print"
> function:
> 
> print('''Ah, so your name is %s, your quest is %s, and your
>     favorite color is %s.''' % (name, quest, color))

Exactly correct.



-- 
Steven



More information about the Python-list mailing list