perl style formating

Andrew Dalke dalke at
Fri Dec 14 22:59:11 EST 2001

Les Ander:
>say i wanted to print out 3 variable in the following format:
>$name is left justified and has the width of size 10
>$comment is left justified and starts at column 11 and ends at 40
>$line starts at 41 and is of variable length)

>>> name = "Les"
>>> comment = "posted to"
>>> line = "xyzzy"
>>> print "%(name)-10s %(comment)-30s%(line)s" % vars()
Les        posted to              xyzzy
0         1         2         3         4

>in perl i would write it as:
>format OUT =
>@<<<<<<<<<< >@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<    >@*
>$name, $comment, $line;

Ahhh, that's a different question.  I've never used Perl's
format mechanism despite the tens of 1,000s of Perl I wrote.
However, trying it out just now I see that "<<<" will truncate
if there's more than 3 characters in the result.  The code I
gave in Python doesn't do that.

But then, your spec didn't ask for it.

There was a story I heard in school about some other student
who switched majors a few times.  Typically it takes about
120 credit hours to graduate, though a few people might get
up near 200.  He managed to get more than 250 hours (so twice
what most people need to graduate).  His grades were good, so
his total number of "grade points" (A = 4.0 = best, B = 3.0, ...)
was over 1,000.

Some part of the program truncated grade points to three
digits -- effectively doing modulo 1000 -- then used the result
to compute the GPA (grade points / credit hours).  When
submitting his transcript to prospective employers he had to
include a note pointing out why his GPA was near 0.0 (failure)
instead of near 4.0.

So Perl's truncation method might not be the best.  Then again,
Python's might not be best when dealing with strict column
based formats.  A 3rd option is FORTRAN, which fills overflowed
fields with "*" to show the field could not be properly
expressed, and do so without disturbing the column locations.
(It is FORTRAN after all.)

In other words, don't complain that the Python solution isn't
the same as the Perl one because it might be that neither
have the best/most appropriate solution.

(Hmmm, from Stanford, learning Python, from google you've
used bioperl -- wonder if I'm (indirectly) through Jeff and
Biopython the reason for your learning Python.  ;)

                    dalke at

More information about the Python-list mailing list