Is there any way to use variables in multiline string in Python? [duplicate]

拟墨画扇 提交于 2019-12-10 18:28:11

问题


So I have this as part of a mail sending script:

try:
    content = ("""From: Fromname <fromemail>
    To: Toname <toemail>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: test

    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)

And I'd like to use different subjects each time (let's say it's the function argument).

I know there are several ways to do this.

However, I am also using ProbLog for some of my other scripts (a probabilistic programming language based in Prolog syntax). As far as I know, the only way to use ProbLog in Python is through strings, and if the string is broke in several parts; example = ("""string""", variable, """string2"""), as well as in the email example above, there's no way I can make it work.

I actually have a few more scripts where using variables in multiline strings could be useful, but you get the idea.

Is there any way to make this work? Thanks in advance!


回答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))


来源:https://stackoverflow.com/questions/35903017/is-there-any-way-to-use-variables-in-multiline-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!