473,323 Members | 1,550 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,323 software developers and data experts.

better way than: myPage += 'more html' , ...

Hi everyone,

I have a python cgi program that uses print statements to write html.
The program has grown, and for reasons I won't bore you with, I need to
build the page in a string and "print" it at once.

I remember reading somewhere that building the string with successive
"+=" statements is inefficient, but I don't know any alternatives, and
my search attempts came up empty. Is there a better, more efficient way
to do it than this:

#---------------------------------
htmlPage = "<html><header></header><body>"
htmlPage += "more html"
....
htmlPage += "even more html"
....
htmlPage += "</body></html>"
print htmlPage
#-------------------------------------

Thanks, Gobo

Jul 18 '05 #1
11 2832
Gobo Borz wrote:
I remember reading somewhere that building the string with successive
"+=" statements is inefficient, but I don't know any alternatives, and
my search attempts came up empty. Is there a better, more efficient way
to do it than this:

#---------------------------------
htmlPage = "<html><header></header><body>"
htmlPage += "more html"
...
htmlPage += "even more html"
...
htmlPage += "</body></html>"
print htmlPage
#-------------------------------------


Best to do something like

#---------------------------------

htmlbits = []
htmlbits.append("<html><header></header><body>")
htmlbits.append("more html")
# ...
htmlbits.append("even more html")
# ...
htmlbits.append("</body></html>")

# And now for the non-intuitive bit
print "".join(htmlbits)

#---------------------------------

HTH,

--
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan: http://xhaus.com/mailto/alan
Jul 18 '05 #2
Gobo Borz wrote

I remember reading somewhere that building the string with successive
"+=" statements is inefficient, but I don't know any alternatives, and
my search attempts came up empty. Is there a better, more efficient way
to do it than this:

#---------------------------------
htmlPage = "<html><header></header><body>"
htmlPage += "more html"
...
htmlPage += "even more html"
...
htmlPage += "</body></html>"
print htmlPage
#-------------------------------------


Instead, build up a list of strings, then join them all at
the end - this way, the system only has to allocate the
space once. Much quicker.

#---------------------------------
htmlPage = []
htmlPage.append("<html><header></header><body>")
htmlPage.append("more html")
...
htmlPage.append("even more html")
...
htmlPage.append("</body></html>")
page = ''.join(htmlPage)
print page
#-------------------------------------

Anthony

Jul 18 '05 #3
On Wednesday 25 Jun 2003 5:20 pm, Gobo Borz wrote:
Hi everyone,

I have a python cgi program that uses print statements to write html.
The program has grown, and for reasons I won't bore you with, I need to
build the page in a string and "print" it at once.

I remember reading somewhere that building the string with successive
"+=" statements is inefficient, but I don't know any alternatives, and
my search attempts came up empty. Is there a better, more efficient way
to do it than this:

#---------------------------------
htmlPage = "<html><header></header><body>"
htmlPage += "more html"
...
htmlPage += "even more html"
...
htmlPage += "</body></html>"
print htmlPage
#-------------------------------------

Thanks, Gobo

An easy way, which requires little changes tou your code would be to use a
list and join it up into a string in one go at the end:

-----------8<--------------
htmlPage=["<html><header></header><body>\n"]
htmlPage.append("more html\n")
....
htmlPage.append("more html\n")
....
htmlPage.append("<\body><\html>\n")
htmlDoc="".join(htmlPage)
-----------8<--------------

This is more efficient, as the string joining is done all at the same time,
rather than in little chunks.

hope that helps
-andyj
Jul 18 '05 #4
Thanks Alan, Anthony, and Andy! B's thru Z's need not respond, I have
my answer.

--Gobo
Gobo Borz wrote:
Hi everyone,

I have a python cgi program that uses print statements to write html.
The program has grown, and for reasons I won't bore you with, I need to
build the page in a string and "print" it at once.

I remember reading somewhere that building the string with successive
"+=" statements is inefficient, but I don't know any alternatives, and
my search attempts came up empty. Is there a better, more efficient way
to do it than this:

#---------------------------------
htmlPage = "<html><header></header><body>"
htmlPage += "more html"
...
htmlPage += "even more html"
...
htmlPage += "</body></html>"
print htmlPage
#-------------------------------------

Thanks, Gobo


Jul 18 '05 #5
Thanks, that opens up a world of possibilities I haven't began to
explore. In general, I'm not fond of templating systems because of the
overhead, but it seems as your suggestion might be fast, since it uses
ordinary string substitution.

--Gobo

mi*********@zeibig.net wrote:
In article <3E************@yahoo.com>, Gobo Borz wrote:
I remember reading somewhere that building the string with successive
"+=" statements is inefficient, but I don't know any alternatives, and
my search attempts came up empty. Is there a better, more efficient way
to do it than this:

#---------------------------------
htmlPage = "<html><header></header><body>"
htmlPage += "more html"
...
htmlPage += "even more html"
...
htmlPage += "</body></html>"
print htmlPage
#-------------------------------------


Hello Gobo,

you may use the list solution provided in the former chapters. Some other
solution would be to use string substitution:
--------- snip -----------
htmlPage = """
<html>
<head>
<title>%(title)s</title>
</head>
<body>
<h1>%(title)s</h1>
%(body)s
</body>
</html>
"""

body = []
body.append("<p>my first snippet</p>")
body.append("<ul>")
for in range(10):
body.append("""<li>%s. entry</li>""" % i)
body.append("</ul>")

contents = { "title": "My Foopage",
"body": "\n".join(body) }

print htmlPage % contents
-------- snap -------------

This type of substitution goes for a very simple templating system.

Best Regards
Mirko


Jul 18 '05 #6
Gobo Borz wrote:
I have a python cgi program that uses print statements to write html.
The program has grown, and for reasons I won't bore you with, I need to
build the page in a string and "print" it at once.


Another way, which has not yet been mentioned but which I like much,
is the cStringIO module. You can write to a string as if it is a
file:

0 >>> import cStringIO
1 >>> mystr = cStringIO.StringIO()
2 >>> mystr.write("<html")
3 >>> mystr.write("<body>")
4 >>> mystr.write("<h1>Header</h1>")
5 >>> mystr.write("<p>Hello, world!</p>")
6 >>> mystr.write("</body></html>")
10 >>> mystr.getvalue()
'<html<body><h1>Header</h1><p>Hello, world!</p></body></html>'

The cStringIO module is documented at:

http://www.python.org/dev/doc/devel/...-StringIO.html

cStringIO is a faster C implementation with the same API.

yours,
Gerrit.

--
196. If a man put out the eye of another man, his eye shall be put out.
-- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
http://www.sp.nl/

Jul 18 '05 #7
#Gobo Borz wrote:
#> Thanks, that opens up a world of possibilities I haven't began to
#> explore. In general, I'm not fond of templating systems because of the
#> overhead, but it seems as your suggestion might be fast, since it uses
#> ordinary string substitution.
#

Often an adapter is a good choice:
class HtmlViewAdapter:

"""
Base class that Adapts any object to html output.
"""

def __init__(self, obj):
self._obj = obj

def __getattr__(self, attr):
"Returns values for the attributes"
return getattr(self._obj, attr)

def __getitem__(self, item):
"get attrs as items for use in string formatting templates"
value = getattr(self, item)
if callable(value):
return value()
else:
return value

import time

class SomeObject:

"The object we want displayed in html"
def __init__(self):
self.id = 42
self.now = time.localtime()
self.title = 'the title'

class SomeObjectHtmlView(HtmlViewAdapter):

"""
an adapter for the object, here you can fine adjust, format dates
etc.
"""

def title(self):
return self._obj.title.upper()

def now(self):
return time.strftime('%y:%m:%d %H-%M-%S',self._obj.now)
view = SomeObjectHtmlView(SomeObject())

print '<a href="%(id)s">%(title)s</a> <i>%(now)s</i>' % view
<a href="42">THE TITLE</a> <i>03:06:26 00-12-16</i>


Jul 18 '05 #8
Gobo Borz wrote:
Hi everyone,

I have a python cgi program that uses print statements to write html.
The program has grown, and for reasons I won't bore you with, I need to
build the page in a string and "print" it at once.


Hi!

I do it like this:

def foo(mydict):
ret=[]

rows=[]
for key, value in mydict.items():
rows.append('<tr><td>%s</td><td>%s</td></tr>' % (key, value))
rows=''.join(rows)

ret.append('<table>%s</table>' % rows)
return ''.join(ret)

I try to keep the start-tag and the end-tag in one string.
This keeps the code from becomming ugly.

thomas

Jul 18 '05 #9
[Max M]
I remember reading a post where I saw meassurements that showed it to be
twice as fast. I was too lazy too google it. But here goes. [...]
[Adrien Di Mascio]
I've a made a quite basic test on these methods : [...]


Thanks to both! Have a good day!

--
François Pinard http://www.iro.umontreal.ca/~pinard

Jul 18 '05 #10
Adrien Di Mascio wrote:
I've a made a quite basic test on these methods :

/snip/

def write_thousands_join(self, char):
"""Writes a 100000 times 'char' in a list and joins it
"""
str_list = []
for index in range(100000):
str_list.append(char)

return ''.join(str_list)


no time to repeat your tests, but

def write_thousands_join(self, char):
"""Writes a 100000 times 'char' in a list and joins it
"""
str_list = []
append = str_list.append # bind method to local variable
for index in range(100000):
append(char)

return ''.join(str_list)

"should" be slightly faster.

also note that the results "may" differ somewhat if you append strings
of different lengths (mostly due to different overallocation strategies;
or maybe they're not different anymore; cannot remember...)

I always use join, but that's probably because that method is more likely
to run code that I once wrote. Never trust code written by a man who
uses defines to create his own C syntax ;-)

</F>


Jul 18 '05 #11
I have a question with regards to the sprintf style of replacing
strings. I have a table in my HTML with a 50% width specifier. How
can i get the formatter to ignore it. For example in the example
below how can i code the 50% to be ignored?

keep the "%s 50% %s" % ("a","b")
Jul 18 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

220
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have...
5
by: MAK | last post by:
I'm stumped. I'm trying to use Python 2.3's urllib2.urlopen() to open an HTML file on the local harddrive of my WinXP box. If I were to use, say, Netscape to open this file, I'd specify it as...
5
by: Lukas Holcik | last post by:
Hi everyone! How can I simply search text for regexps (lets say <a href="(.*?)">(.*?)</a>) and save all URLs(1) and link contents(2) in a dictionary { name : URL}? In a single pass if it could....
4
by: Steven T. Hatton | last post by:
You can scroll down to the last line of this post in order to find the question I really want to discuss. I was just pondering the competing applicability of C vs. C++ in certain problem...
20
by: Nick | last post by:
Right now I'm using document.write("<script language='javascript' src='jsFile" + i + ".js'></script>"); It works -- I have a lot of data in each file and only want the visitor to have to...
2
by: Bryan Olson | last post by:
The current Python standard library provides two cryptographic hash functions: MD5 and SHA-1 . The authors of MD5 originally stated: It is conjectured that it is computationally infeasible to...
0
by: Pavils Jurjans | last post by:
Hello, Please, I am fighting with this now for two days, and getting nowhere: I have my application in a separate virtual folder: c:\www\myApp There is a bin folder there:
43
by: Rob R. Ainscough | last post by:
I realize I'm learning web development and there is a STEEP learning curve, but so far I've had to learn: HTML XML JavaScript ASP.NET using VB.NET ..NET Framework ADO.NET SSL
6
by: Michael | last post by:
Hi, A quick and most likely simply question about which is generally better programming with PHP. Is it more proper to break out of PHP code to write HTML, or is it ok rto do it within print()...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.