Python:在多行字符串中使用变量

问题描述

我有两个变量:

subject = 'this is the subject'
body = 'this is the content'

对于使用smtplib发送每封电子邮件,我将我的message变量作为多行字符串。但是.format()方法不起作用。有没有人想解决这个问题?

消息字符串:

    message = """\
    Subject: (variable subject)


    (variable content)"""

解决方法

为简单起见,可以使用f字符串:

message = f"""
    Subject: {subject}


    {body}"""

此处提供使用format()的正确方法:

message = """
subject = {}


{}
""".format(subject,body)

要使用格式,请将{}放在需要添加变量的位置,然后使用变量 顺序 的列表声明.format()希望将这些{}替换为

,

尝试一下:

>>> subject = 'this is the subject'
>>> body = 'this is the content'
>>> message = '''\
... Subject: {subject}
...
{{ 1}}
... {body}\
... '''.format(subject=subject,body=body)
>>> print(message)
Subject: this is the subject

Try this

,

我不确定您指的是什么,但这是我最好的猜测:

message = 'Subject: {}\n\n{}'.format(subject,body)
,

@ juanpa.arrivillaga

我的尝试:

message = """\
    Subject: {.format(subject)}


    Python test"""

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...