簡體   English   中英

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

[英]Python: Use Variable in mulit-line string

我有兩個變量:

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

為了使用 smtplib 發送每封電子郵件,我將消息變量作為多行字符串。 但是 .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}
...
... {body}\\
... '''.format(subject=subject, body=body)
>>> print(message)
Subject: this is the subject
this is the content

嘗試這個

我不完全確定,你指的是什么,但這是我最好的猜測:

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

@juanpa.arrivillaga

我的嘗試:

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


    Python test"""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM