print and % operator

Josef Meile jmeile at hotmail.com
Thu Sep 9 09:44:01 CEST 2004


Hi Ruchika,

 > I am new to Python, so this may be a very simple question for most of
 > you. What does the % operator stand for in Python?
It is an operator for formating strings. Ie: lets say you want to print 
a string followed by an integer value embebbed on a string, then you 
could do:

myStr='Test'
value=10
print "String: %s value: %i" % (myStr, value)

This will print:
String: Test value: 10

You could do the same by concatenating the strings:
print "String: " + myStr + "value: " + str(value)

However, the first piece of code is easier to understand and faster.

This link may help:
http://docs.python.org/lib/typesseq-strings.html#l2h-206


 >I came across a
> script that uses the % operator as follows -
> 
> def sync(delf,name):
>     os.popen3( 'P4 -s sync -f %s' % name)
> 
> I would suspect that this just replaces the %s with the value of name.
That's right.

> Is % before name required?
Yes, % is required since you included "%s" on the string, so, you have 
to match it with some variable/constant. If you use "%i" instead, then 
you will have to use an int variable/constant.

 >Should there be a space between % and name?
No, you could use:
os.popen3( 'P4 -s sync -f %s'%name)

but it looks ugly and it's difficult to read.

> On a similar note, how can I print the value of name using the print
> statement? Should print %name print the value of name?
No, if you want to print a variable directly you should use:
print name

if you want to print it inside a string then you should do:
print "This is the value of name: %s" % name

> 
> Most of the time, when I add some print statements to my script I get
> Autoindent error. Can someone tell me what this error is and how to
> fix it?
Indentation may be wrong, check if you are using the same number of 
tabs/spaces on each indentation level.

Regards,
Josef



More information about the Python-list mailing list