Translating a Perl script into Python

Hamish Lawson hamish_lawson at yahoo.co.uk
Sat Jan 20 20:22:40 EST 2001


Sheila King wrote:

> and then at the end you list in parenthese the later stuff, behind a
> % sign.

It's more general and more powerful than that. The % operator takes a
string on the left and a single value, tuple, list or dictionary on the
right and produces a string by substituting the % placeholders in the
left-hand operand with values from the right-hand operand. Note that %
inside a string doesn't have any special meaning in itself; it's the %
operator that treats it as placeholder. Thus

    a = "His name is %s and his age is %d"
    b = ['Bob', 42]
    print a % b

gives

    His name is Bob and his age is 42

> The %s in the string is taking the place for something that comes
> later

The % is a placeholder and the 's' indicates that it is to be formatted
as a string; other symbols are 'd' for decimal and 'f' for floating-
point number. Various other symbols can appear between the % and the
type symbol. Thus the following:

    print "%.2f" % 345.6788

formats the supplied value as a floating-point number with two digits
after the decimal point:

   345.68

If the left-hand side of the % operator is a list, then the values are
substituted for the placeholders sequentially. If a dictionary is being
used, then you can specifying the key to be associated with a given
placeholder by using the notaion "%(key)s". Here are some examples:

    # Using a tuple literal
    PROC.write("%s is %d\n" % ('Bob', 42))

    # Using a list variable
    data = ['Bob', 42]
    PROC.write("%s is %d\n" % data)

    # Using a dictionary literal
    data = {'name': 'Bob', 'age': 42}
    PROC.write("%(name)s is %(age)d\n" % {'name': 'Bob', 'age': 42})

    # Using a dictionary variable
    data = {'name': 'Bob', 'age': 42, 'title': 'Widget washer'}
    PROC.write("%(name)s is %(age)d\n" % data)

    # Using locals() to give a dictionary of local variables
    name = 'Bob'
    age = 42
    title = 'Widget washer'
    PROC.write("%(name)s is %(age)d\n" % locals())

The last one is closest to the Perl example.

Hamish Lawson


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list