1

Is it possible to do dynamic string substitution with Python's string.Template ? More precisely I don't want to replace occurrences of identifiers with results of functions, e.g.

from string import Template

f = lambda s: "123"

templateString = """first line: $replaceme
2nd line "$replaceme" """

s = Template(templateString).substitute(replaceme=f)

Instead of evaluating f its string representation is used:

first line: <function <lambda> at 0x7fb0367e3488>
2nd line "<function <lambda> at 0x7fb0367e3488>"

Any ideas how to do substitution with the result of f ?

1 Answer 1

2

You need to call f by doing f(). f means the function; f() means its return value.

Sign up to request clarification or add additional context in comments.

2 Comments

If using f() the evaluation is done once for all occurrences of replaceme. My intention was to call f for each occurrence.
@StefanArmbruster: Pretty sure that's not possible with the way you're doing it. The placeholder in the template has to specify a static value, not an expression, so if you use $replaceme both times, you have to get the same value both times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.