escaping/encoding/formatting in python

Steve Howell showell30 at yahoo.com
Thu Apr 5 21:56:08 EDT 2012


One of the biggest nuisances for programmers, just beneath date/time
APIs in the pantheon of annoyances, is that we are constantly dealing
with escaping/encoding/formatting issues.

I wrote this little program as a cheat sheet for myself and others.
Hope it helps.

  # escaping quotes
  legal_string = ['"', "'", "'\"", '"\'', """ '" """]
  for s in legal_string:
    print("[" + s + "]")

  # formatting
  print 'Hello %s' % 'world'
  print "Hello %s" % 'world'
  planet = 'world'
  print "Hello {planet}".format(**locals())
  print "Hello {planet}".format(planet=planet)
  print "Hello {0}".format(planet)

  # Unicode
  s = u"\u0394"
  print s # prints a triangle
  print repr(s) == "u'\u0394'" # True
  print s.encode("utf-8") == "\xce\x94" # True
  # other examples/resources???

  # Web encodings
  import urllib
  s = "~foo ~bar"
  print urllib.quote_plus(s) == '%7Efoo+%7Ebar' # True
  print urllib.unquote_plus(urllib.quote_plus(s)) == s # True
  import cgi
  s = "x < 4 & x > 5"
  print cgi.escape(s) == 'x < 4 & x > 5' # True

  # JSON
  import json
  h = {'foo': 'bar'}
  print json.dumps(h) == '{"foo": "bar"}' # True
  try:
    bad_json = "{'foo': 'bar'}"
    json.loads(bad_json)
  except:
    print 'Must use double quotes in your JSON'

It's tested under Python3.2.  I didn't dare to cover regexes.  It
would be great if somebody could flesh out the Unicode examples or
remind me (and others) of other common APIs that are useful to have in
your bag of tricks.






More information about the Python-list mailing list