escaping/encoding/formatting in python

Nobody nobody at nowhere.com
Sat Apr 7 01:36:14 EDT 2012


On Fri, 06 Apr 2012 06:22:13 -0700, rusi wrote:

> But are not such cases rare?

They exist, therefore they have to be supported somehow.

> For example code such as:
> print '"'
> print str(something)
> print '"'
> 
> could better be written as
> print '"%s"' % str(something)

Not if the text between the delimiters is large.

Consider:

	print 'static const char * const data[] = {'
	for line in infile:
	    print '\t"%s",' % line.rstrip()
	print '};'

Versus:

	text = '\n'.join('\t"%s",' % line.rstrip() for line in infile)
	print 'static const char * const data[] = {\n%s\n};' % text

C++11 solves the problem to an extent by providing raw strings with
user-defined delimiters (up to 16 printable characters excluding
parentheses and backslash), e.g.:

	R"delim(quote: " backslash: \ rparen: ))delim"

evaluates to the string:

	quote: " backslash: \ rparen: )

The only sequence which cannot appear in such a string is )delim" (i.e. a
right parenthesis followed by the chosen delimiter string followed by a
double quote). The delimiter can be chosen either by analysing the string
or by choosing something a string at random and relying upon a collision
being statistically improbable.




More information about the Python-list mailing list