Strange tab problem!
Peter Otten
__peter__ at web.de
Mon Aug 25 03:18:28 EDT 2003
tjland at iserv.net wrote:
> for x in title_author.keys():
> print "Book: ",x," \tAuthor: ",title_author[x],"
> \tCopyright:",title_copyright[x]
>
> it seems that whenever i go over six characters it adds another tab. Is
> there a preset field limit to six bytes. What is happening? Thanx in
> advance.
Note that Python inserts a space between the arguments of a print statement.
So you *always* get (replacing space with "S" and tab with "T")
"Book:SSxSS(book title):SSTAuthor:SS(author name)TCopyright:S(year)"
123456789a(book title)123
How this is displayed, depends on your editor settings. Assuming 1 tab == 8
spaces:
"Tb" -> "SSSSSSSSb"
"1Tb" -> "1SSSSSSSb"
"12Tb" -> "12SSSSSSb"
...
"1234567Tb" -> "1234567Sb"
"12345678Tb" -> "12345678SSSSSSSSb"
So every time you reach the 8 character limit, another tab appears to be
(but is not!) inserted. Solution:
(1) do not use tabs, and
(2) calculate column widths before printing
title_author = {"For whom the bell tolls": "Hemingway",
"Zauberberg": "Mann"}
title_copyright = {"For whom the bell tolls": 1234,
"Zauberberg": 123}
titleWidth = max(map(len, title_author.keys()))
authorWidth = max(map(len, title_author.values()))
copyrightWidth = max(map(lambda y: len(str(y)), title_copyright.values()))
for title in title_author.keys():
ptitle = title.ljust(titleWidth)
pauthor = title_author[title].ljust(authorWidth)
pcopyright = str(title_copyright[title]).rjust(copyrightWidth)
print "Book:", ptitle, "Author:", pauthor, "Copyright", pcopyright
The generalization for arbitrary tables (and finding out the samples' years
of publication) is left as an exercise to the OP :-)
Peter
More information about the Python-list
mailing list