[Tutor] Cosmetic question about printing
Dick Moores
rdm at rcblue.com
Wed May 7 00:04:57 CEST 2008
At 04:55 PM 5/5/2008, Steve Willoughby wrote:
>On Tue, May 6, 2008 11:35, Dick Moores wrote:
>
> > Could someone just come right out and do it for me? I'm lost here.
> > That '*' is just too magical.. Where did you guys learn about
> > '%*s'? Does the '%s' still mean a string?
>
>Python's % operator (for string formatting) is derived from the C standard
>library function printf(), which also accepts the %*s notation. It's
>capable of a lot of powerful features you may not be aware of. See
>printf(3) for full details (you can google for printf if you don't have
>manpages on your system).
>
>In a nutshell, between the % and the s you can put the desired field
>width, like "%10s" which means to pad out the data in the string to be at
>least 10 characters, right-justifying the column. "%-10s" means to left
>justify it. If the string being printed is longer than that, it's just
>printed as-is, it's not truncated. But you can specify that if you like,
>too: "%10.10s"
>
>In place of either of those numbers, you can use "*" which just means
>"pick up the desired width from the next value in the tuple", which allows
>you to compute the width on the fly, which is what's being done here.
>
>Try this:
>
>def print_result(date1, date2, days1, weeks, days2):
> line1 = 'The difference between %s and %s is %d day%s' % (
> date1.strftime('%m/%d/%Y'),
> date2.strftime('%m/%d/%Y'),
> days1, ('' if days1 == 1 else 's'))
> line2 = 'Or %d week%s and %d day%s' % (
> weeks, ('' if weeks == 1 else 's'),
> days2, ('' if days2 == 1 else 's'))
>
> print line1
> print '%*s' % (len(line1), line2)
I just found your reply in my Tutor mailbox, at the HEAD of the
thread I started. By my time (U.S. PDT), you answered my 07:11 AM
5/6/2008 post at 04:55 PM 5/5/2008!
Received: from 134.134.136.14
(SquirrelMail authenticated user steve)
by webmail.alchemy.com with HTTP;
Mon, 5 May 2008 16:55:30 -0700 (PDT)
But I'm glad I noticed it. That's a very clear explanation of '%'
and '*'. Thanks!
You worked in a nice algorithm for pluralizing regular nouns. Thanks
for that, too.
Dick Moores
More information about the Tutor
mailing list