1

Possible Duplicate:
Python format tabular output

How do I get the output of the following code (Python 2.7), to be in a table?

with open('blacklists.bls', 'r') as f:
        L = [dnsbls.strip() for dnsbls in f]
t10 = time.time()
for listofdnsbls in L:
        try:
                t0 = time.time()
                result = socket.gethostbyname("%s.%s" % (ip_reversed(iinput), listofdnsbls))
                t1 = time.time()
                total = t1-t0
                print "%s\t%s\t%s sec" % (listofdnsbls, result, total)
        except (socket.gaierror):
                t2 = time.time()
                error_total = t2-t0
                print "%s\tNo result\t%s sec" % (listofdnsbls, error_total)
t20 = time.time()
totaltotal =t20-t10
print "\nCompleted in: %s sec" % (totaltotal)

At the moment the output isn't very tidy:

rbl.ntvinet.net 77.95.250.11    0.00194096565247 sec
postfix.bondedsender.org    No result   0.329633951187 sec
procmail.bondedsender.org   No result   6.34444999695 sec

I'd like it to be more like this:

rbl.ntvinet.net             77.95.250.11    0.00194096565247 sec
postfix.bondedsender.org    No result       0.329633951187 sec
procmail.bondedsender.org   No result       6.34444999695 sec

I've found a few documents explaining to use %1d and %2d, but I couldn't get that to work, as they aren't numbers but strings.

Community
  • 1
  • 1
MadsRC
  • 139
  • 1
  • 3
  • 10

1 Answers1

3

You can use a number within a %s modifier as well. The sign of the number determines whether the string will be left or right aligned. E.g. %20s for right aligned strings and %-20s for left aligned strings.

Dov Grobgeld
  • 4,783
  • 1
  • 25
  • 36
  • He was using \t in order to get tabbed columns, which doesn't work if the string is longer than the tab width. %99s on the other hand will always work if you know the maximum length. And if you don't you can loop through your entries and extract the maximum length and then build the formatting dynamically. – Dov Grobgeld Jan 23 '13 at 13:07
  • That actually helped me get the desired output :) Problem was that the links I found wasn't really that well explained. Guess if I used a couple of hours to fully understand it, they would make sense :) – MadsRC Jan 23 '13 at 13:14