4

This question has been answered before, but my string doesn't have any extra curly brackets that would mess up the formatting, so at the moment I'm completely clueless as to why the error

Error is KeyError : content

html = """
    <table class=\"ui celled compact table\" model=\"{model}\">
        {theaders}
        <tbody>
            {content}
        </tbody>
    </table>
    """
html = html.format(model=model)
html = html.format(content=data)
html = html.format(theaders=theaders)
2
  • 2
    Aside: The backslashes are not required in this example. Part of the benefit of triple-quoting a string is that any individual quote character is no longer special. Commented Dec 19, 2016 at 19:36
  • I just did them as part of trying to figure out the error :) Commented Dec 19, 2016 at 19:40

2 Answers 2

11

you could do it line by line using a dictionary and passing the dict as keyword arguments using **

d=dict()
d['model']=model
d['content']=data
d['theaders']=theaders

html = html.format(**d)
Sign up to request clarification or add additional context in comments.

Comments

7

you need to fill the values in one go:

html.format(model=model, content=data, theaders=theaders)

8 Comments

is there no way of doing it in parts?
@Mojimi Not directly via str.format(). Template strings have this feature using safe_substitute() but with a different placeholder syntax. But why do you need it?
yes, you could. you'd need to surround content with double brackets; theaders with four brackets ({model}...{{content}}..{{{{theaders}}}}). a bit of a hack...
Template strings are the answer!
@Mojimi html = Template(html).safe_substitute(model=model); html = Template(html).safe_substitute(content=data). But I really would suggest the approach from @jean-françois-fabre 's answer
|

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.