Search code examples
pythonstringstring-interpolation

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


Solution

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