有没有办法在Python中的多行字符串中使用变量?

3 python string string-interpolation

所以我将此作为邮件发送脚本的一部分:

try:
    content = ("""From: Fromname <fromemail>
    To: Toname <toemail>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: test

    This is an e-mail message to be sent in HTML format

    <b>This is HTML message.</b>
    <h1>This is headline.</h1>
    """)
Run Code Online (Sandbox Code Playgroud)

...

    mail.sendmail('from', 'to', content)
Run Code Online (Sandbox Code Playgroud)

我想每次都使用不同的主题(让我们说它是函数参数).

我知道有几种方法可以做到这一点.

但是,我也使用ProbLog来处理我的一些其他脚本(一种基于Prolog语法的概率编程语言).据我所知,在Python中使用ProbLog的唯一方法是通过字符串,如果字符串在几个部分中断了; example =("""string""",variable,"""string2"""),以及上面的电子邮件示例中,我无法使其工作.

我实际上有一些脚本,在多行字符串中使用变量可能很有用,但你明白了.

有没有办法让这项工作?提前致谢!

L3v*_*han 7

使用.format方法:

content = """From: Fromname <fromemail>
    To: {toname} <{toemail}>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: {subject}

    This is an e-mail message to be sent in HTML format

    <b>This is HTML message.</b>
    <h1>This is headline.</h1>
"""
mail.sendmail('from', 'to', content.format(toname="Peter", toemail="p@tr", subject="Hi"))
Run Code Online (Sandbox Code Playgroud)

一旦最后一行变得太长,您可以改为创建一个字典并将其解压缩:

peter_mail = {
    "toname": "Peter",
    "toemail": "p@tr",
    "subject": "Hi",
}
mail.sendmail('from', 'to', content.format(**peter_mail))
Run Code Online (Sandbox Code Playgroud)