Trivial string substitution/parser

Duncan Booth duncan.booth at invalid.invalid
Sun Jun 17 07:00:58 EDT 2007


Samuel <newsgroups at debain.org> wrote:

> Hi,
> 
> How would you implement a simple parser for the following string:
> 
> ---
> In this string $variable1 is substituted, while \$variable2 is not.
> ---
> 
> I know how to write a parser, but I am looking for an elegant (and lazy) 
> way. Any idea?
> 
The elegant and lazy way would be to change your specification so that $ 
characters are escaped by $$ not by backslashes. Then you can write:

>>> from string import Template
>>> t = Template("In this string $variable1 is substituted, while 
$$variable2 is not.")
>>> t.substitute(variable1="hello", variable2="world")
'In this string hello is substituted, while $variable2 is not.'

If you must insist on using backslash escapes (which introduces the 
question of how you get backslashes into the output: do they have to be 
escaped as well?) then use string.Template with a custom pattern.




More information about the Python-list mailing list