Python discoveries

Saturday 26 October 2002

I've been using Python for a few years now, but I'm still discovering useful tidbits:

1. The encode method on strings. Want to quickly see how a Unicode string comes out in UTF-8?:

>>> u"\u201c".encode('utf-8')
'\xe2\x80\x9c'

2. The % operator (as in sprintf, not modulo) has a named argument syntax (which seems not to be mentioned in the Python Language Reference, but I discovered it in the Python/Perl phrasebook):

>>> d = {'a': 1, 'b': 2}
>>> "b is %(b)s, a is %(a)s" % d
'b is 2, a is 1'

Comments

Add a comment:

name
email
Ignore this:
not displayed and no spam.
Leave this empty:
www
not searched.
 
Name and either email or www are required.
Don't put anything here:
Leave this empty:
URLs auto-link and some tags are allowed: <a><b><i><p><br><pre>.