Moving from PHP to Python. Is it Possible

MRAB python at mrabarnett.plus.com
Fri Dec 11 11:58:26 EST 2009


zeph wrote:
[snip]
> 4) It's better to collect all your eventual output into a string that
> you print - there are examples at [3]. You can import from other
> modules as needed (even conditionally), grow your string for output,
> then finally print it like (this example was adapted from one found on
> [3]):
> 
> output =  '<html><head>'
> output += '<title>My Page</title>'
> output += '</head><body>'
> output += '<h1>Powers of two</h1>\n<ol>'
> for n in range(1,11):
>   output += '<li>'+str(2**n)+'</li>'
> 
> output += '</ol></body></html>'
> print output
> 
> 
> You can copy-paste this right into your Python interactive shell to
> see the output. Note: += is inline string concatenation.
> 
It's better to put the strings into a list and then concatenate them in
one go:

output = ['<html><head>']
output.append('<title>My Page</title>')
output.append('</head><body>')
output.append('<h1>Powers of two</h1>\n<ol>')
for n in range(1, 11):
     output.append('<li>%s</li>' % (2 ** n))

output.append('</ol></body></html>')
print ''.join(output)



More information about the Python-list mailing list