How do I speedup this loop?

Steve nospam at nopes
Thu Jul 15 19:55:26 EDT 2004


george young wrote:
> On Wed, 14 Jul 2004 15:40:15 -0400
> Bart Nessux <bart_nessux at hotmail.com> threw this fish to the penguins:
> 
> 
>>george young wrote:
>>
>>>How about:
>>>
>>>lines = []
>>>out = os.popen('some command')
>>>for l in out:
>>>    lines.append(l.strip())
>>>script = ''.join(lines)
>>>out.close()
>>>
>>>The "strip" actually removes white space from front and back of the string;
>>>you could say l.strip('\n') if you only want the newlines removed (or '\r'
>>>if they're really carriage return characters.)
>>
>>The above is a great solution... should make for a good speed up. It's 
>>how I might pproach it.
>>
>>
>>>Or if you want a clever (and most CPU efficient!) one-liner:
>>>
>>>script = ''.join([l.strip() for l in os.popen('some command')])
> 
> [fixed up a bit...I forgot about the join]
> 
>>Clever progammers should be shot! I've had to work behind them... they 
>>are too smart for their own good. They think everyone else in the world 
>>is as clever as they are... this is where they are wrong ;)
> 
> 
> Oh, all right.  How about:
> 
>     out = os.popen('some command')
>     temp_script = [l.strip() for l in out]
>     script = ''.join(temp_script)

That looks good but the problem is that I don't want to 'strip' off the 
'end of line' characters etc., because I need to reproduce/print the 
output exactly as it was at a later stage. What's more... I need to 
print it out on a HTML page, and so if I know the different between \n 
(in code) and the implicit end of line character, I can interpret that 
in HTML accordingly. For example, the output can contain something like:

printf("Hey there\n");

and so, there's a \n embedded inside the text as well as the end of line 
character which isn't visible. Although escaping characters using a 
DB-API  function might do the trick, this still won't help me much in 
the end, where I need to print a "<br>" for each 'end of line character'.

-- 
Steve
> 
> That's clear enough, and still takes advantage of the efficiency of
> the list comprehension!  (I admit, that for reading the whole file,
> the other postings of regexp substitution on the total string are
> certainly faster, given enough RAM, but still not as clear and concise
> and elegant ... blah blah blah as mine...
> 
> -- George Young
> 




More information about the Python-list mailing list