Search code examples
pythonpython-3.xstring-substitution

How to read multiple lines in a template and substitute values?


I have a piece of standard text having multiple lines and some format like below:

owner: oracle
date_conditions: 1
    timezone: US/Eastern
    std_out_file: "/app/local/job.log"
    machine: rachost

I want to use this above text with machine and timezone being changed as per the need. How can I use python to define this is a template and substitute various values? I came across the substitution option in string.Template. But this seems to be working with a single line only.


Solution

  • The string.Template class can handle strings consisting of multiple lines.

    For example:

    from string import Template
    
    template = Template('''\
    owner: oracle
    date_conditions: 1
        timezone: $tz
        std_out_file: "/app/local/job.log"
        machine: $mach
    ''')
    
    result = template.substitute(tz='US/Pacific', mach='foobar')
    print(result, end='')
    

    Prints:

    owner: oracle
    date_conditions: 1
        timezone: US/Pacific
        std_out_file: "/app/local/job.log"
        machine: foobar