Welcome, guest | Sign In | My Account | Store | Cart

A simple (but not hopelessly fragile) approach for string substitution.

Python, 15 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import sys

if sys.version_info[:2] > (2, 2):
    def dequote(string, dictionary):
        """Replace quoted parts of string with dictionary entries."""
        parts = string.split('"')
        parts[1::2] = [dictionary[word] for word in parts[1::2]]
        return ''.join(parts)
else:
    def dequote(string, dictionary):
        """Replace quoted parts of string with dictionary entries."""
        parts = string.split('"')
        for i in range(1, len(parts), 2):
            parts[i] = dictionary[parts[i]]
        return ''.join(parts)

Often we need string substitution and the "%(name)s" format for Python's string operations is simply not particularly readable. While this code is _very_ simple, it allows easy-to-read source to be converted. It does rely on your string not using a quote, but you can getaround that by adding a dictionary entry: {"":QUOTE} that converted empty strings (doubled quotes) to the quote mark.

Replacing "dictionary[word]" with "Dictionary.get(word, word.join(QUOTE+QUOTE))" might work better for your application; it simply leaves quoted anything not found in the dictionary.

Of course this also works with variations on the EvalClass class alluded to (and deprecated by) Orin Tirosh:

<pre> class EvalDict: def __init__(self, dictionary, locals=None, globals=None): self.dictionary = dictionary.copy() self.dicts = [locals, globals] if globals is None: self.dicts = [locals] if locals is None: del self.dicts[0]

def __getitem__(self, expr):
      try:
          return self.dictionary[expr]
      except KeyError, e:
          self.dictionary[expr] = str(eval(expr, *self.dicts))
          return self.dictionary[expr]

expandedText = dequote("""This is "name" demonstrating "__name__".""", EvalDict({'name':'Scott'}, locals(), globals())) </pre>