Is There Any Way To Use Variables In Multiline String In Python?
So I have this as part of a mail sending script: try: content = ('''From: Fromname To: Toname MIME-Version: 1.0 Content-type: text
Solution 1:
Using the .format
method:
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"))
Once that last line gets too long, you can instead create a dictionary and unpack it:
peter_mail = {
"toname": "Peter",
"toemail": "p@tr",
"subject": "Hi",
}
mail.sendmail('from', 'to', content.format(**peter_mail))
As of Python 3.6, you can also use multi-line f-strings:
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>
"""
Post a Comment for "Is There Any Way To Use Variables In Multiline String In Python?"