views:

69

answers:

4

I have a for loop which references a dictionary and prints out the value associated with the key. Code is below:

for i in data:
    if i in dict:
        print dict[i],

How would i format the output so a new line is created every 60 characters? and with the character count along the side for example:

0001 MRQLLLISDLDNTWVGDQQALEHLQEYLGDRRGNFYLAYATGRSYHSARELQKQVGLMEP
0061 DYWLTAVGSEIYHPEGLDQHWADYLSEHWQRDILQAIADGFEALKPQSPLEQNPWKISYH
0121 LDPQACPTVIDQLTEMLKETGIPVQVIFSSGKDVDLLPQRSNKGNATQYLQQHLAMEPSQ

A: 

it seems like you're looking for textwrap

SilentGhost
A: 
# test data
data = range(10)
the_dict = dict((i, str(i)*200) for i in range( 10 ))

# your loops as a generator
lines = ( the_dict[i] for i in data if i in the_dict )

def format( line ):
    def splitter():
        k = 0
        while True:
            r = line[k:k+60] # take a 60 char block
            if r: # if there are any chars left
                yield "%04d %s" % (k+1, r) # format them
            else:
                break
            k += 60
    return '\n'.join(splitter()) # join all the numbered blocks

for line in lines:
        print format(line)
THC4k
+1  A: 

It's a finicky formatting problem, but I think the following code:

import sys

class EveryN(object):
  def __init__(self, n, outs):
    self.n = n        # chars/line
    self.outs = outs  # output stream
    self.numo = 1     # next tag to write
    self.tll = 0      # tot chars on this line
  def write(self, s):
    while True:
      if self.tll == 0: # start of line: emit tag
        self.outs.write('%4.4d ' % self.numo)
        self.numo += self.n
      # wite up to N chars/line, no more
      numw = min(len(s), self.n - self.tll)
      self.outs.write(s[:numw])
      self.tll += numw
      if self.tll >= self.n:
        self.tll = 0
        self.outs.write('\n')
      s = s[numw:]
      if not s: break

if __name__ == '__main__':
  sys.stdout = EveryN(60, sys.stdout)
  for i, a in enumerate('abcdefgh'):
    print a*(5+ i*5),

shows how to do it -- the output when running for demonstration purposes as the main script (five a's, ten b's, etc, with spaces in-between) is:

0001 aaaaa bbbbbbbbbb ccccccccccccccc dddddddddddddddddddd eeeeee
0061 eeeeeeeeeeeeeeeeeee ffffffffffffffffffffffffffffff ggggggggg
0121 gggggggggggggggggggggggggg hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
0181 hhhhhhh
Alex Martelli
A: 

I haven't tested it on actual data, but I believe the code below would do the job. It first builds up the whole string, then outputs it a 60-character line at a time. It uses the three-argument version of range() to count by 60.

s = ''.join(dict[i] for i in data if i in dict)
for i in range(0, len(s), 60):
    print '%04d %s' % (i+1, s[i:i+60])
Daniel Stutzbach