[Tutor] File parsing

Alan Gauld alan.gauld at btinternet.com
Fri Jun 17 11:06:49 CEST 2011


"Neha P" <mywrkid at yahoo.com> wrote

for eachline in f_obj:
     eachline=eachline[ :-1]# to eliminate the trailing "\n"

Better to use rstrip() here, thee might be extraneous spaces etc
to remove too.

     list_words=eachline.split(" ")

list_words[0]=list_words[0]+"\n"# to add "\n" so that after line 1 is 
printed, line 2 should start on a new line

I'd do this at the end after you print the line, otherwise if
you later decide to rearrange the words you have to
remember to remove the \n from that specific word.
You don't really want that word to have a \n you want
the printed line to have a \n, so put it on the line not
the word.

list_words.reverse()
for every_word in list_words:
print every_word,# 'comma' helps in printing words on same line,hence 
for last word we append "\n"

You could use join() and just print that:

print ' '.join(list_words)

And print will now add the newline for you.

HTH,

Alan G.




More information about the Tutor mailing list