newbie question concerning formatted output

Bengt Richter bokr at oz.net
Tue Nov 29 23:36:59 EST 2005


On Tue, 29 Nov 2005 17:40:08 GMT, Thomas Liesner <t.liesner at creativ-consulting.de> wrote:

>Hello all,
>
>i am having some hard time to format the output of my small script. I am
>opening a file which containes just a very long string of hexdata
>seperated by spaces. Using split() i can split this string into single
>words and print them on stdout. So far so good. But i want to print always
>three of them in a single line and after that a linebreak.
>
>So instead of:
>
>3905
>3009
>0000
>4508
>f504
>0000
>3707
>5a07
>0000
>etc...
>
>i'd like to have:
>
>3905 3009 0000
>4508 f504 0000
>3707 5a07 0000
>etc...
>
>This is the codesnippet i am using:
>
>#!/usr/bin/python
>
>import string
>inp = open("xyplan.nobreaks","r")
>data = inp.read()
>for words in data.split():
>        print words
>inp.close()
>
>Any hints?
>
Using StringIO(""" ... """) in place of open("xyplan.nobreaks","r"),
(BTW, "r" is the default, and can be left out)

 >>> from StringIO import StringIO
 >>> ins = (line.strip() for line in StringIO("""\
 ... 3905
 ... 3009
 ... 0000
 ... 4508
 ... f504
 ... 0000
 ... 3707
 ... 5a07
 ... 0000
 ... """))
 >>> for tup in zip(ins, ins, ins):
 ...     print '%s %s %s' % tup
 ...
 3905 3009 0000
 4508 f504 0000
 3707 5a07 0000

Or if the zip(it, it) grouping idiom is not politically correct, you could use
itertool.izip instead, or groupby with a grouping function that returns changing
constants for each group of three, e.g.,

 >>> from StringIO import StringIO
 >>> ins = (line.strip() for line in StringIO("""\
 ... 3905
 ... 3009
 ... 0000
 ... 4508
 ... f504
 ... 0000
 ... 3707
 ... 5a07
 ... 0000
 ... """))
 >>> import itertools
 >>> for k,g in itertools.groupby(ins, lambda _, c=itertools.count().next: c()//3):
 ...     print '%s %s %s' % tuple(g)
 ...
 3905 3009 0000
 4508 f504 0000
 3707 5a07 0000

Regards,
Bengt Richter



More information about the Python-list mailing list