将值传递给 html inside string in python

Pass value to html inside string in python

我有以下代码:

def smtp_mailer(name,email):
    html = """\
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
 <style type="text/css">
.h1, .p, .bodycopy {color: #153643; font-family: sans-serif;}
  .h1 {font-size: 33px; line-height: 38px; font-weight: bold;}
</style>
</head>
<body>

<h1>This is a {name}</h1>
<p>This is a {email).</p>

</body>
</html> 
"""
    part2 = MIMEText(html, 'html')
    msg.attach(part2) 

当我发送 SMTP 邮件时,我无法在 HTML 的 h1 标签处传递值作为名称,在 p 标签处传递电子邮件的值。请帮帮我。 谢谢。

您可以像这样使用 string interpolation

def smtp_mailer(name,email):
    html = f"""\
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a {name}</h1>
<p>This is a {email}.</p>

</body>
</html> 
"""
    print(html)

smtp_mailer("test", "test@test.test")

Returns

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a test</h1>
<p>This is a test@test.test.</p>

</body>
</html>

在最初的评论之后,似乎被问到的主要问题是字符串包含一些大括号(即 {} 字符),这些大括号将作为文字保留在字符串中<style> 元素的一部分,还有那些打算作为格式说明符的一部分被替换的元素。

鉴于此字符串是您自己的代码,您可以将其修改为预期的内容,而不是外部提供的值,您必须为此不一致找到不可避免的混乱解决方法,适当的解决方案是将本应是字面量的{}改为{{}},这样在调用format方法后,它们将输出为单大括号.

这样做之后(同时也纠正了{email)末尾的错误字符),就可以应用format方法:

例如,

html = """\
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
 <style type="text/css">
.h1, .p, .bodycopy {{color: #153643; font-family: sans-serif;}}
  .h1 {{font-size: 33px; line-height: 38px; font-weight: bold;}}
</style>
</head>
<body>

<h1>This is a {name}</h1>
<p>This is a {email}.</p>

</body>
</html> 
""".format(name="John", email="test@example.com")

print(html)

给出:

...
.h1, .p, .bodycopy {color: #153643; font-family: sans-serif;}
  .h1 {font-size: 33px; line-height: 38px; font-weight: bold;}
...
<h1>This is a John</h1>
<p>This is a test@example.com.</p>
...

正如其他人提到的(在 Python 3 中),您也可以使用 f 字符串表示法而不是显式调用 format 方法,前提是您有要使用的值已替换为名为 nameemail 的变量。在任何情况下,您仍然需要在格式化之前将文字大括号加倍。