Ramblings

March 17, 2008

Enhanced python string interpolation

Filed under: cool, dev, python — michaelangela @ 2:39 pm

This particular module is a bit older, but it’s supposed to work with Python 2.x. There may be a newer one floating around but I’ll have to check for that. Either way, it’s pretty cool.

Python things

This module lets you quickly and conveniently interpolate
values into strings (in the flavour of Perl or Tcl, but with
less extraneous punctuation). You get a bit more power than
in other languages, because this module allows subscripting,
slicing, function calls, attribute lookup, or arbitrary expressions.
Here are the simple interpolation rules:

  1. A dollar sign and a name, possibly followed by any of:
    • an open paren, and anything up to the matching paren
    • an open bracket, and anything up to the matching bracket
    • a period and a name

    any number of times, is evaluated as a Python expression.

  2. A dollar sign immediately followed by an open curly-brace,
    and anything up to the matching curly-brace, is evaluated as
    a Python expression.
  3. Two dollar signs in a row give you one literal dollar sign.
  4. Anything else is left alone.

Expressions are evaluated in the namespace of the caller.
This lets you painlessly do:

"Here is a $string."

"Here is a $module.member."

"Here is an $object.member."

"Here is a $functioncall(with, arguments)."

"Here is an ${arbitrary + expression}."

"Here is an $array[3] member."

"Here is a $dictionary['member']."
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: