0

I have a XML form with parameters in the following way:

<Text>Answer the Question</Text>
<Text>Q${ID}: ${Text}:</Text>

With this xml text file, I want to replace the parameters in ${ } with corresponding values. For example, if I have the following values:

ID = '1', Text = 'Capital of Michigan is'

then I want the result to be:

<Text>Answer the Question</Text>
<Text>Q1: Capital of Michigan is:</Text>

Other than this feature, the program imports a csv file and then writes new files. So I am trying to write it in Python. What is the best way to do the above functionality in Python?

2 Answers 2

1

You really need to know what template format was intended here, so you can use the right templating engine.

This example does happen to match the format of string.Template in the standard library. Whether that actually exactly matches the intended format, or just happens to be close enough for this example, is hard to say. If you don't have anything more complicated than ${identifier} anywhere, it will work.

So:

>>> xml_template = '''<Text>Answer the Question</Text>
<Text>Q${ID}: ${Text}:</Text>'''
>>> ID = '1'
>>> Text = 'Capital of Michigan is'
>>> xml = string.Template(xml_template).substitute(ID=ID, Text=Text)
>>> xml
'<Text>Answer the Question</Text>\n<Text>Q1: Capital of Michigan is:</Text>'

You may also want to use safe_substitute, or to pass **locals() instead of passing explicit arguments, or to actually store your variables in a dict instead of as a bunch of separate variables, etc. Read the docs for further details and examples.

If your pattern format is more complicated, you can customize string.Template (again, see the docs), but you have to understand the complex template dialect you're trying to customize for… and that makes it even more of a good idea to figure out what template engine the patterns were written for and use something compatible.

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

Comments

0

Since you are copying a template format the easiest way is to use a templating language which has already implemented those constructs. One option is mako and the syntax is as follows (From mako webpage):

from mako.template import Template
print(Template("hello ${data}!").render(data="world"))

1 Comment

Python has built-in support for this style in string.Template, so there's no need to go grab a third-party library just for this.

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.