0

I'm wondering what the difference is between two statements. I want to print a variable in a <p> html tag. Both statements do the same thing but one give me an error.

The first statement that works:

out += "</p><p style=""background-color:white"">"
out += uSetMinF
out += "</p><p>"

The second one that doesn't work:

out += "<p style=""background-color:white"">"uSetMinF"</p>"

Here's the error that I get:

out += "<p style=""background-color:white"">"uSetMinF"</p>"
                                                    ^
SyntaxError: invalid syntax

Although the first statement works, I'd rather use the second one because it saves time and it's a little less code. I know it's semantics but I'm also curious. If someone knows the answer please let me know, thanks.

3 Answers 3

3

To concatenate literal strings and variables you have to use the + operator:

out += "<p style=""background-color:white"">" + uSetMinF + "</p>"

This is equivalent to your first example, but probably incorrect for what you want. The resulting string will be the following:

<p style=background-color:white>whatever uSetMinF is</p>

There are no quotes around the style value. This is because Python treats

"<p style=""background-color:white"">"

as if it was

"<p style=" "background-color:white" ">"

i.e. three separate string literals. In comparison to variables, Python concatenates consecutive string literals without the need of the + operator.

If you want to preserve the quotes in your quoted string, you have two options:

  1. Escape the inner quotes:

    out += "<p style=\"background-color:white\">" + uSetMinF + "</p>"

  2. Mix single- and double-quotes:

    out += '<p style="background-color:white">' + uSetMinF + '</p>'

Sign up to request clarification or add additional context in comments.

Comments

0

The quotation are used to enclosure the strings, use backslash to escape them or use single quotation mark: ' as the first AND last

Comments

0

I know that this question is a bit old but there is a better solution:

you can use the .format() or the %s. e.g

out += '<p style="background-color:white">%s</p>' % str(uSetMinF)

or

out += '<p style="background-color:white">{0}</p>'.format(uSetMinF)

Comments

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.