String changing on the fly

John Hunter jdhunter at ace.bsd.uchicago.edu
Wed Oct 20 13:40:56 EDT 2004


>>>>> "John" == John Hunter <jdhunter at nitace.bsd.uchicago.edu> writes:


Continuing the fun, you can define a new python class that inherits
from string, but overrides the "convert me to a string representation"
method __str__ to evaluate itself in the context of the global
variables

import re


class PerlString(str):
    def __str__(self):

        rgx = re.compile('\$(\w+)')
        fmt = re.sub('\$(\w+)', self.dollar_replace, self)
        return fmt%globals()

    def dollar_replace(self, matchobj):
        return '%(' + matchobj.group(1) + ')s'

s = PerlString('$first paid cost $T dollars')


T = 2
first = 'John'
print s

T = 5
first = 'Bill'
print s






More information about the Python-list mailing list