word replacing in a paragraph

Chris Angelico rosuav at gmail.com
Mon Jan 6 10:16:36 EST 2014


On Tue, Jan 7, 2014 at 1:01 AM, Frank Cui <ycui at outlook.com> wrote:
> I'm trying to automate a process by initially creating a standard template
> and then replace some text fields with variable values.
>
> [for example, "DATE" in the paragraph will be replaced by the current date
> value. it doesn't have to be a literal word of "DATE", "DATE" in "TESTDATE"
> can also be replaced.]

How much do you trust the person creating that template? If it's you
yourself, then probably the easiest way is to use the inbuilt
str.format() method or %-formatting:

template = """Today is: %(date)s
Test ran on %(version)s, in %(time)f seconds."""

data = {"date":"2014-01-07", "version":"v3.4.0b2", "time":123.45}

print(template % data)

Today is: 2014-01-07
Test ran on v3.4.0b2, in 123.450000 seconds.

This gives you a lot of flexibility, as you can lay things out tidily
as well as simply substituting in values.

ChrisA



More information about the Python-list mailing list