Python: Use Variable in mulit-line string

2.5k views Asked by At

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)"""
4

There are 4 answers

3
Ironkey On BEST ANSWER

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

0
Marius On

I'm not entirely sure, what you are referring to, but this is my best guess:

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

@juanpa.arrivillaga

My Try:

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


    Python test"""
1
Shaheryar On

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

Try this