Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,有没有办法在多行字符串中使用变量?_Python_String_String Interpolation - Fatal编程技术网

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

在Python中,有没有办法在多行字符串中使用变量?,python,string,string-interpolation,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

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

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>
    """)
我希望每次都使用不同的主题(假设是函数参数)

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

然而,我也在为我的一些其他脚本(一种基于Prolog语法的概率编程语言)使用ProbLog。 据我所知,在Python中使用ProbLog的唯一方法是通过字符串,如果字符串被分成几个部分;示例=(“string”、变量“string2”)以及在上面的电子邮件示例中,我无法使其正常工作

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

有什么办法可以让这一切顺利进行吗?
提前谢谢

使用
.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"))

从Python 3.6开始,还可以使用多行f字符串:

toname = "Peter"
toemail = "p@tr"
subject = "Hi"
content = f"""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>
"""
toname=“Peter”
电子邮件=”p@tr"
主题=“嗨”
content=f“From:Fromname
收件人:{toname}
MIME版本:1.0
内容类型:text/html
主题:{Subject}
这是以HTML格式发送的电子邮件
这是一条HTML消息。
这是标题。
"""

我不明白您想做什么。您似乎想要多行
字符串,而不是多行注释。在注释中使用变量没有任何意义-注释不会被执行。Python没有多行注释。三重引号字符串不是注释。没错。很抱歉多行字符串。我是python新手。我只是没想过。这个问题被错误地标记为。。。这个问题不是重复的,因为另一个问题不涉及使用多行字符串
peter_mail = {
    "toname": "Peter",
    "toemail": "p@tr",
    "subject": "Hi",
}
mail.sendmail('from', 'to', content.format(**peter_mail))
toname = "Peter"
toemail = "p@tr"
subject = "Hi"
content = f"""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>
"""