alexs973
alexs973

Reputation: 183

Python string concatenation

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.

Upvotes: 0

Views: 5169

Answers (3)

Rafael Ortega
Rafael Ortega

Reputation: 454

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)

Upvotes: 0

Pit
Pit

Reputation: 4046

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>'

Upvotes: 3

gbriones.gdl
gbriones.gdl

Reputation: 536

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

Upvotes: 0

Related Questions