newbie question concerning formatted output

Bengt Richter bokr at oz.net
Wed Nov 30 00:53:34 EST 2005


On Tue, 29 Nov 2005 17:40:08 GMT, Thomas Liesner <t.liesner at creativ-consulting.de> wrote:
[...]
>This is the codesnippet i am using:
Sorry, I made no comment on your actual code. Some follows.
>
>#!/usr/bin/python
>
>import string
I'm not seeing the need for importing string

>inp = open("xyplan.nobreaks","r")
 inp = open("xyplan.nobreaks") # defaults to "r"

>data = inp.read()
>for words in data.split():
At this point words would have to be a group of three successive words,
joined with a single space separator. So we can still use your loop
and only print with newline on the last of every group of three. So
we can use a counter to tell where in the cycle we are, e.g., combining
read() and split() and enumerating the split sequence, (untested)

 for i, words in enumerate(inp.read().split()):
    if i%3 < 2:
         print words, # trailing comma makes a space separator if next print continues line output
    else: # do as before and print final word with newline
>        print words
       
>inp.close()
>
>Any hints?

Upgrade if you don't have 2.4 ;-)
Then you can do a oneliner with a single print ;-)

Set up the data file example:

 >>> open('xyplan.nobreaks','w').write("""\
 ... 3905
 ... 3009
 ... 0000
 ... 4508
 ... f504
 ... 0000
 ... 3707
 ... 5a07
 ... 0000
 ... """)

Show it as is:

 >>> print '----\n%s----'%open('xyplan.nobreaks').read()
 ----
 3905
 3009
 0000
 4508
 f504
 0000
 3707
 5a07
 0000
 ----

Now the one-liner, FWIW ;-)

 >>> print '\n'.join(' '.join(z) for it in [(ln.strip() for ln in open('xyplan.nobreaks'))] for z in (zip(it, it, it) ))
 3905 3009 0000
 4508 f504 0000
 3707 5a07 0000

Regards,
Bengt Richter



More information about the Python-list mailing list