2012-11-17 118 views
4

我在Python中编写了一个非常简单的搜索引擎,并且必须使用HTML代码创建一个带有表格的HTML页面。这是我给使用代码:在变量中包含引号

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

这看起来Python的文件的罚款之外,但我需要更换汽车租赁与变量关键字。当我尝试将以<h2>开头的行作为变量存储以便使用.replace方法时,会出现问题。 Python由于中间的引用而感觉到语法错误。有没有办法将这个变量存储为变量?或者还有另外一种方法可以替代这些词吗?

回答

5

用一个反斜杠逃逸,或使用一个单引号字符串,或使用"""长块:

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> 
""" 
0

这就是像PHP和Python,单引号字符串之间的互换性语言的很大一部分双引号字符串,只要内部引号与外部引号相反即可。更重要的是,Python在两者之间进行切换时,并不会改变escape的工作方式。但是,对于PHP,单引号字符串不会处理单引号和反斜线以外的转义。例如:

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

长块字符串不能用于连接,您将需要使用.replace(),这比串接更昂贵。