Mark J Seger
Mark J Seger

Reputation: 367

What does the % in a print between the format and variables actually do?

I'm just starting to fool around with formatting the output of a print statement.

The examples I've seen have a % after the format list and before the arguments, like this:

>>> a=123
>>> print "%d" % a
123

What is the meaning of the % and more important, why is it necessary?

Upvotes: 0

Views: 118

Answers (3)

bgporter
bgporter

Reputation: 36564

Also note that this style of string formatting is referred to in the documentation as "old string formatting"; moving forward we should move to the new-style string formatting as described here: http://docs.python.org/library/stdtypes.html#str.format

like:

>>> a=123
>>> print "{0}".format(a)
123

See Format String Syntax for a description of the various formatting options that can be specified in format strings.

This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.

Upvotes: 1

unwind
unwind

Reputation: 400109

It's the string formatting operator, it tells Python to look at the string to the left, and build a new string where %-sequences in the string are replaced with formatted versions of the values from the right-hand side of the operator.

It's not "necessary", you can print values directly:

>>> print a
123

But it's nice to have printf()-style formatting available, and this is how you do it in Python.

As pointed out in a comment, note that the string formatting operator is not connected to print in any way, it's an operator just like any other. You can format a value into a string without printing it:

>>> a = 123
>>> padded = "%05d" % a
>>> padded
00123

Upvotes: 7

Geoff Reedy
Geoff Reedy

Reputation: 36071

In python the % operator is implemented by calling the method __mod__ on the left hand argument, falling back to __rmod__ on the right argument if it's not found. So what you have written is equivalent to

a = 123
print "%d".__mod__(a)

Python's string classes simply implement __mod__ to do string formatting.

Upvotes: 4

Related Questions