简体   繁体   中英

Python: Use Variable in mulit-line string

i have two variables:

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

For sending this per e-mail with smtplib i have my message variable as an multi line string. But the .format() method doesn't work. Has anybody an idea to solve this?

The message String:

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


    (variable content)"""

You can use an f string for simplicity:

message = f"""
    Subject: {subject}


    {body}"""

Heres the right way to use format() :

message = """
subject = {}


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

to use format, place {} where your variables need to be added and then declare .format() with a sequential list of the variables you want those {} 's to be replaced with

Try this:

>>> 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

My Try:

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


    Python test"""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM