Htmlizing text

Gerrit Holl gerrit.holl at pobox.com
Tue Nov 30 14:12:24 CET 1999


William Park wrote:
> On Mon, Nov 29, 1999 at 09:03:46PM +0000, Phil Hunt wrote:
> > 
> > Is there a function in the standard Python library to HTML-ize text,
> > i.e. to replace 'a > b & c < d' with 'a > b & c < d'?
> > 
> > (I realize this can be done with regular expressions, but is there
> > an easy way?)
> > 
> > -- 
> > Phil Hunt - - - phil at comuno.com
> 
> The following function replaces [<&>] unconditionally.
>     def escapeall(s):
> 	s = string.replace(s, '&', '&')		# do this first
> 	s = string.replace(s, '<', '<')
> 	s = string.replace(s, '>', '>')
> 	return s
> I used this in my 'HTMLtag' module which generates HTML tags.

This is better:

def escapeall(s):
	import htmlentitydefs
	for k, v in htmlentitydefs.items():
		s = string.replace(s, v, '&' + k)
	return s

By the way, why doesn't the cgi module does this?

regards,
Gerrit.

-- 
"The move was on to 'Free the Lizard'"

  -- Jim Hamerly and Tom Paquin (Open Sources, 1999 O'Reilly and Associates)
  2:08pm  up 35 min,  4 users,  load average: 0.00, 0.00, 0.08




More information about the Python-list mailing list