user1442957
user1442957

Reputation: 7729

python iterating strings

I am writing the content of "article" to a text file.

Source file:

lol hi
lol hello
lol text
lol test

Python:

for line in all_lines:
    if line.startswith('lol '):
        mystring = line.replace('lol ', '').lower().rstrip()

article = 'this is my saved file\n' + mystring + '\nthe end'

This is what gets saved to the txt file:

this is my saved file
test
the end

This is what I want saved to the txt file:

this is the saved file
hi
hello
test
text
the end

Upvotes: 1

Views: 135

Answers (3)

Simeon Visser
Simeon Visser

Reputation: 122476

You are replacing the string each time. You will want to store the results of each lol line and then add them all to mystring:

mystring = []
for line in all_lines:
    if line.startswith('lol '):
        mystring.append(line.replace('lol ', '', 1).lower().rstrip() + '\n')

article = 'this is my saved file\n'+''.join(mystring)+'\nthe end'

In the above code, I've turned mystring into list which is then turned into a string at the end using the join method. Note that I've added a newline (\n) character to each line as you want that character in your output (and rstrip() removes it). Alternatively, you can write:

line.replace('lol ', '', 1).lower().rstrip(' ')

which lets rstrip() only strip spaces and not all other forms of whitespace.


Edit: An alternative approach is to write:

mystring.append(line.replace('lol ', '').lower().rstrip())

and:

article = 'this is my saved file\n'+'\n'.join(mystring)+'\nthe end'

Upvotes: 5

jamylak
jamylak

Reputation: 133634

You could take this different approach:

with open('test.txt') as fin, open('out.txt', 'w') as fout:
    fout.write('this is my saved file\n')
    for line in fin:
        if line.startswith('lol '):
            fout.write(line.replace('lol ', '').lower())
    fout.write('the end')

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56684

... or as a one-liner,

mystring = ''.join(line[4:].lower() for line in all_lines if line.startswith('lol '))

Upvotes: 0

Related Questions