A critique of cgi.escape

Duncan Booth duncan.booth at invalid.invalid
Sun Oct 8 05:49:43 EDT 2006


Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> wrote:

> Another useful function is this:
> 
>     def JSString(Str) :
>         """returns a JavaScript string literal that evaluates to Str.
>         Note I'm not worrying about non-ASCII characters for now."""
<snip>

Here is a shorter alternative that handles non-ASCII sequences provided you 
pass in unicode:

def JSString(s):
	return repr(unicode(s))[1:]

>>> print JSString(u"\u201chi there!\u201d")
'\u201chi there!\u201d'
>>> print JSString("Hello world")
'Hello world'
>>> print JSString("Hello 'world'")
"Hello 'world'"

For ascii strings you could also use the string-escape codec, but strangely 
the unicode-escape codec doesn't escape quotes.



More information about the Python-list mailing list