Entry
What is this symbol use for % ?...besides percent :-)
Jun 23rd, 2002 14:34
Michael Chermside, Don Mills,
The % sign is used for two things in Python.
The first is computing a modulus (also known as "remainder"). This works
just like in C:
>>> 17 % 5
2
It returns the remainder, so 5 into 17 goes 3 times with a remainder of
2, thus 17 % 5 gives 2. In case you were wondering, the (best) way to
get the other value (the "div") is "//" (as in 17 // 3 --> 3), but on
older versions of Python it may not be present and you will need to use
"/" instead.
The % operator works for lots of different kinds of numbers:
>>> (17 + 18j) % (5 + 7j)
(7+4j)
>>> 12345678987654321L % 7
1L
>>> 3.14 % 2
1.1400000000000001
The OTHER use for the % sign is string interpolation. Here is a simple
example:
>>> name = 'George'
>>> print 'Bow to King %s' % name
Bow to King George
This is the same operator that is used for computing modulus, but when
it's left-hand argument is a string, it does something completely
different. Basically, it searches through the string (the left-hand
argument) for any % signs. The % sign is treated as the beginning of a
C-style format string so, for insance %i is used to insert an integer,
or %s to insert a string, or even %3i for an integer padded to 3
characters. '%%' is used to insert a literal percent character. If there
are multiple % escapes, than the right-hand argument of the operator may
(should!) be a tuple with as many items as there are % escapes in the
string, and the values in this are interpolated.
>>> a = 'apple'
>>> b = 'bananna'
>>> other = ['orange', 'kumquat']
>>> 'Some fruits are %s, %s, and also %s.' % (a, b, other)
"Some fruits are apple, bananna, and also ['orange', 'kumquat']."
The various values are inserted in the same order that they appear in
the tuple. If you want to identify things by name, not order, you can
use a dictionary:
>>> fruits = {'a': 'apple', 'b': 'bananna', 'best': 'cherry'}
>>> '%(a)s and %(b)s are good, but %(best)s is best.' % fruits
'apple and bananna are good, but cherry is best.'
More information on the use of string interpolation can be found at
http://python.org/doc/current/lib/typesseq-strings.html