Gary E. Miller <g...@rellim.com>: > Yo All! > > Yet another undocumented Python failure: > > i>>> d = {} > >>> d[1] = "one" > >>> d[2] = "two" > >>> str(d[2]) > 'two' > >>> echo "%s(d[2])s" % locals > File "<stdin>", line 1 > echo "%s(d[2])s" % locals > ^ > SyntaxError: invalid syntax > > > Python says %s(x)s works for any x that str(x) works. > > Here is the Python doc: > > https://docs.python.org/2.7/library/stdtypes.html#string-formatting > > "'s' String (converts any Python object using str())." > > WRONG!
No, RIGHT! The syntax error was triggered by "echo", which isn't a Python keyword. Your shell reflexes got the better of you <s>and you shot the sheriff.</s>. If you do the right thing and use print instead, here's what will happen. The %s part will stringize the right argument of %, which in this case is a dict; it will be rendered into a dict literal. Then it will literally emit the string "(d[2])s". If you had any different belief about what would happen, you misread the documentation. There is one mildly dangerous curve here. The syntax of "print" changes in 3.x; best way to be safe is to use the directive from __future__ import print_function which will make recent 2.x versions use functional syntax. Note to self: Add a section on good Python practice to the Hacking Guide. -- <a href="http://www.catb.org/~esr/">Eric S. Raymond</a>
signature.asc
Description: PGP signature
_______________________________________________ devel mailing list devel@ntpsec.org http://lists.ntpsec.org/mailman/listinfo/devel