Yuval
Yuval

Reputation: 21

python string assignment

I have a StringIO object the is filled correctly. I than have the following code:

val = log_fp.getvalue()
lines = val.split('\n') 
newval = ''
for line in lines:
    if (not line.startswith('[output]')):
        newval = line   
        print 'test1'+newval    
print 'test2' +newval

in the loop, I have the correct value for newval printed, but in the last print, I have an empty string. Any ideas what I am doing wrong? What I need is to extract one of the lines in the stringIO object that is marked [output], but newval seems to be empty in 'test2'.

Upvotes: 2

Views: 199

Answers (3)

Andrea Spadaccini
Andrea Spadaccini

Reputation: 12651

What I need is to extract one of the lines in the stringIO object that is marked [output],

Untested:

content = log_fp.getvalue().split()
output_lines = [x for x in content if x.startswith('[output'])]

Then get the first element of output_lines, if that is what you need.

Upvotes: 1

kevpie
kevpie

Reputation: 26088

Splitting on '\n' for a string such as 'foo\n' will produce ['foo', ''].

Upvotes: 4

winwaed
winwaed

Reputation: 7801

Is log_fp a text file? If so, the last value in lines will be everything after the last newline character. Your file probably terminates in a newline, or a newline and some whitespace. For the former case, the last value of line will be an empty string. For the latter case, the last value of line will be the whitespace.

To avoid this, you could add a new clause to the if statement to check the trimmed string is not empty, eg.

val = log_fp.getvalue()
lines = val.split('\n') 
newval = ''
for line in lines:
    if ( len(line.strip()) > 0):
        if (not line.startswith('[output]')):
            newval = line   
            print 'test1'+newval    
print 'test2' +newval

(I haven't tried running this, but it should give you the idea)

Upvotes: 0

Related Questions