String changing on the fly

Hans Nowak hans at zephyrfalcon.org
Wed Oct 20 22:02:21 CEST 2004


John Hunter wrote:

> 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

Mooi hoor, but this only works for global variables.  It won't work with 
variables inside a function, unless you extend the function to pass in 
locals.

Maybe something like this would be a reasonable alternative:

 >>> T = 2
 >>> first = 'Bill'
 >>> def makestr(*args):
...     args = map(str, args)
...     return ''.join(args)
...
 >>> makestr("My name is ", first, " and I paid $", T, " dollars")
'My name is Bill and I paid $2 dollars'

--Hans




More information about the Python-list mailing list