coverting list back to string

Robin Munn rmunn at pobox.com
Tue Apr 22 14:37:21 EDT 2003


I rearranged your post so the question-and-answer order makes sense.
(Please don't top-post, see http://www.caliburn.nl/topposting.html for
reasons why).

scn <regnivon at netscape.net> wrote:
> Dialtone <dialtone at despammed.com> wrote in message news:<878yu33a16.fsf at vercingetorix.vercingetorix>...
>> regnivon at netscape.net (scn) writes:
>> 
>> > my quest:  i know that output.write(remove) is not correct.  you
>> > cannot use the 'write' method on a list.  is there a better way to
>> > convert the list to a string after the first element of the list has
>> > been removed and then output the strings to a file?  i'm a newbie
>> > programmer and need guru help. thank you.
>> 
>> Sure:
>> 
>> input = file('c:/python22/programs/linetest.txt', 'r')
>> output = file('c:/python22/programs/output.txt', 'w')
>> 
>> for line in input:
>>     remove = line.split()
>>     remove = remove[1:]
>>     output.write(''.join(remove))
>> 
>> input.close()
>> output.close()
> 
> Thank you for your help.  This worked.  I incorporated your suggestion
> of 'remove = remove[1:]' instead of my original code. I'd like to
> figure out how to get each string to output line-by-line, instead of
> one continuous string. If you have any suggestion, I'd appreciate it.
> Thanks again!

Try adding "output.write('\n')" at the end of your for loop:

    for line in input:
        remove = line.split()
        remove = remove[1:]
        output.write(' '.join(remove))
        output.write('\n')

That will get you a newline after each string. Notice also that I put a
space as the delimiter for the join operation. If you use the empty
string ('') as the delimiter, you'll get the input fields all squashed
together, which is probably not what you wanted.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list