[Tutor] Cosmetic question about printing
Kent Johnson
kent37 at tds.net
Tue May 6 18:07:34 CEST 2008
On Tue, May 6, 2008 at 10:11 AM, Dick Moores <rdm at rcblue.com> wrote:
>
> This script of mine, < http://py77.python.pastebin.com/f2fdcb99c>, has a function that prints the result--the difference in days, and weeks and days, between two dates.
>
> The function is
>
> def printResult(date1, date2, days1, weeks, days2):
> print "\nThe difference between %s and %s is %d days" % (date1.strftime("%m/%d/%Y"),
> date2.strftime("%m/%d/%Y"), days1)
> print 37 * " ",
> print "Or %d weeks and %d days" % (weeks, days2)
> print ((len(str(weeks)) + len(str(days2))) + 57) * "="
>
> An example output is:
>
> The difference between 05/06/2008 and 11/04/2008 is 182 days
> Or 26 weeks and 0 days
> ============================================================
>
> Nicely right-justified, but that's not always the case:
>
> The difference between 07/04/1776 and 09/11/2001 is 82248 days
> Or 11749 weeks and 5 days
> ===============================================================
>
> Isn't there an easier way, something built into Python, that would do the job?
>
You can right-justify in a format operation. You will have to do it in
two steps since the string you want to right-justify is itself the
result of a format operation:
line2 = "Or %d weeks and %d days" % (weeks, days2)
print '%50s' % line2
Instead of 50 you probably want to use the length of the previous
line. You can insert this into the format using * for the length:
print %*s' % (len(line1), line2)
Kent
More information about the Tutor
mailing list