[Tutor] about print()

Alan Gauld alan.gauld at btinternet.com
Mon Jun 6 10:21:58 CEST 2011


"Ryan Wu" <seasideryan at gmail.com> wrote

> I am a newbie of python, and reading 'python essential reference'.
> 
> Now I want to print this  results
> 'a is %d' % a -> a is 42
> 
> with the code
> 
> a = 42
>> test = "'a is %d' % a"

test is now a literal string

>> print( '%20s ->' % test, test)

And this inserts the literal string into the format string then 
prints the literal string

What I think you wanted to do is:

>>> a = 42
>>> test = 'a is %d'

>>> print( '%20s -> %s' % (test, test % a) )

> What is the difference of  print(test) and print ( 'a is %d' % a )?

In test you have the a inside the string delimiters so it is part 
of the string. In the second case a is outside the string and 
gets evaluated as a variable

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list