Adding filename variable into HTML string in Python
Question: I've searched and can't find a solution to this. I'm trying to have the python
code loop through a directory for .mht files. Upon finding files it will write
an iframe html code to a file pointing to the .mht's. I'm having trouble
defining the iframe code to be written and include the filename variables in
the src.

>
>     htmlframe = '''<iframe src="'%s.mht'" class="iframe" scrolling="no"
> frameborder="0" style="width:100%"></iframe><br>''' % os.path.basename
>  

The error I get is below:

>
>     Traceback (most recent call last):File "move.py", line 52, in <module>
>     htmlframe = '''<iframe src="'%s.mht'" class="iframe" scrolling="no"
>     frameborder="0" style="width:100%"></iframe><br>''' % os.path.basename
>     TypeError: not enough arguments for format string  
>  

Thank you in advance for any assistance.


Answer: For rather complex string replacement operations, you should look at template
engines. With such an engine it is usually much easier to keep the overview
and to make modifications later on. A very simple one is built into the
standard library: <https://docs.python.org/2/library/string.html#template-
strings>

Is suffices most of the time!

Example:

    
    
    from string import Template
    
    s = """<iframe src="$filename" class="iframe" scrolling="no"></iframe>"""
    t = Template(s)
    print t.substitute(filename="foobar.mht")
    

Test:

    
    
    python template.py
    <iframe src="foobar.mht" class="iframe" scrolling="no"></iframe>
    

