%s %x %0.2f %04d

Bjorn Pettersen bjorn at roguewave.com
Fri Sep 8 23:51:17 CEST 2000


Brendhan Horne wrote:
> 
> In the beginners instruction manual it states:
> There are other letters that can be placed after the % markers. Some of
> those include:
> %s- for string
> %x- for hexadecimal number
> %0.2f- for a real number with a maximum of 2 decimal places
> %04d- pad the number out to 4 digits with 0's
> 
> That is nice but it gives no examples of how to use them. I tried some of
> the basics
> >>> print 7%s2
> Got an error
> >>> print 7 %s 2
> Got an error
> So if someone could show me some basic one liners that use the modulus with
> the suffix I would appreciate it.  Remember when you do this you are dealing
> with someone who has no knowledge of computer language.

Hope this will get you going (the %s has to be inside a string, and when
that string is followed by "%" and then either a single object, or a
tuple the replacement is done):

>>> "Hello: %s" % "Bob"
'Hello: Bob'
>>> "Age: %d" % 25
'Age: 25'
>>> "Name: %s, Age: %d" % ('Bob', 25)
'Name: Bob, Age: 25'
>>> name = "Bob"
>>> age = 25
>>> s = "Name: %s, Age: %d"
>>> s % (name, age)
'Name: Bob, Age: 25'
>>> import math
>>> "pi (%f) with two decimal digits: %0.2f" % (math.pi, math.pi)
'pi (3.141593) with two decimal digits: 3.14'

-- bjorn




More information about the Python-list mailing list