user1831177
user1831177

Reputation: 41

Include quotation marks in a variable

I'm writing an extremely simple search engine in Python, and must use HTML code to create an HTML page with a table on it. This is the code I'm given to use:

<html>
<title>Search Findings</title>
<body>
<h2><p align=center>Search for "rental car"</h2>
<p align=center>
<table border>
<tr><th>Hit<th>URL</tr>
<tr><td><b>rental car</b> service<td> <a href="http://www.facebook.com">http://www.avis.com</a></tr>
</table>
</body>
</html>

This looks fine outside of the Python file, but I need to replace rental car with the variable KEYWORD. The problem arises when I attempt to store the line beginning with <h2> as a variable in order to use the .replace method. Python senses a syntax error because of the quotations in the middle. Is there a way I can store this as a variable anyway? Or is there another way I must go about replacing these words?

Upvotes: 4

Views: 474

Answers (2)

NobleUplift
NobleUplift

Reputation: 6034

That's a great part of languages like PHP and Python, interchangeability between single-quoted strings and double-quoted strings, so long as interior quotes are the opposite of exterior quotes. More to the point with Python, when changing between the two, it does not change how escapes work. With PHP however, single-quoted strings do not process escapes other than single-quotes and backslashes. Example:

output = '<h2><p align=center>Search for "' + search + '"</h2>'
output = "<h2><p align=center>Search for \"" + search + "\"</h2>"

Long block strings will not work for concatenation, you will need to use .replace(), which is more expensive than concatenation.

Upvotes: 0

Ry-
Ry-

Reputation: 225263

Escape it using a backslash, or use a single-quoted string, or use """ for long blocks:

s = '<h2><p align=center>Search for "rental car"</h2>'
s = "<h2><p align=center>Search for \"rental car\"</h2>"
s = """
<p>This is a <em>long</em> block!</p>
<h2><p align=center>Search for "rental car"</h2>
<p>It's got <strong>lots</strong> of lines, and many "variable" quotation marks.</p>
"""

Upvotes: 5

Related Questions