Dalí
Dalí

Reputation: 112

Insert a variable into a string

I have a simple multi-line string:

import wikipedia

html_str = """
<div class=c-box>
         <img display="none" class=cimg src="http://example.com">
             <h3>Example Information</h3>
              <div class=c-boxcontent>
                <p>

Variable Here
"""+var = wikipedia.summary("Julius Caesar", sentences=2) +"""

                </p>
              </div>
</div>
"""

How do I add a variable inside the .c-box so that it will be part of the HTML? Or is how I did the code right?

Upvotes: 0

Views: 112

Answers (1)

user2555451
user2555451

Reputation:

Concatenating large strings with + is kind of ugly in my opinion. You should only use + when you have a few small strings to concatenate.

A cleaner approach would be to use str.format to insert the value into the string:

html_str = """
<div class=c-box>
         <img display="none" class=cimg src="http://example.com">
             <h3>Example Information</h3>
              <div class=c-boxcontent>
                <p>

{}

                </p>
              </div>
</div>
""".format(wikipedia.summary("Julius Caesar", sentences=2))

Note too that your posted code is actually invalid since assignment is a statement in Python. Meaning, you cannot perform an assignment in the middle of a line.

Upvotes: 3

Related Questions