[Tutor] % function

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 26 Apr 2001 16:48:55 +0200


On  0, Liana Wiehahn <liana@upfrontsystems.co.za> wrote:
> Can somebody please explain to me when you are using the % function and
> explain it to me?

There are two different % operators, one for numbers and one for strings.
The number one computes the remainder of a division:
>>> 4 % 3
1    # Because if you do 4/3, the remainder is 1

You probably meant the string operator :).

The idea is to have a format string, in which you leave some positions open,
so you can fill them in later.

>>> x = "Liana"
>>> "Hello, %s!"  % x
"Hello, Liana!"

This is neater than
>>> "Hello, "+x+"!"
and it quickly becomes a lot better when there's more than one variable.

The %s means that a string can be filled in there. If you have multiple
things to fill in, use a tuple:

>>> "%s, %s, %s, %s and %s" % ("spam","spam","spam","bacon","spam")
"spam, spam, spam, bacon and spam"

There are several different % things you can use, which are available
depends on the C library I think, and there's no good page for a complete
list (try searching for the Linux man printf page, or do man printf if
you're on Unix/Linux).

'%%' simply means a % sign.

%d is used for integers.

>>> '%d' % 4
'4'
>>> '%3d' % 4 # The 4 is the field size. Works for strings too.
'  4'
>>> '%03d' % 4 # Fill the field up with 0s
'004'
>>> '%-3d' % 4 # Align the field to the left, not right
'4  '

The last neat trick is % with a dictionary. You can put give variables you
use in the format string a name, and fill them in with a dictionary:

format = "Agent %(agent)03d's name is %(surname)s. %(name)s %(surname)s."

print format % {
       'agent': 7
       'name': 'James'
       'surname': 'Bond'
       }
       
Prints "Agent 007's name is Bond. James Bond."

I find I hardly ever need other things than %s and %d.

-- 
Remco Gerlich