2

I am trying to e-mail an attachment and am formatting the content of my e-mail message.

For some reason when I do:

 variable = f"""
    email content formatting line 1
    email content formatting line 2
    email content formatting line 3
    """

The lines inside the """ """ don't all turn to string, and the rest of my code below becomes string. Any ideas why?

For example, the msg_text and msg.attach lines turn into string. How do I fix my f-string setup?

html = f"""
    <html><body>
    <h1> Monthly Accounting File ({month_end.strftime("%m/%d/%Y")})</h1>
    <p>{df.to_html(index=False)}</p>
    </body></html>
    """
msg_text = MIMEText(html, 'html')
msg.attach(msg_text)

If I add one space after f then my lines turn to string but I thought that wasn't the correct syntax for f-strings. This is for Jupyter Notebook Python 3.0. See below for example:

html = f """
    <html><body>
    <h1> Monthly Accounting File ({month_end.strftime("%m/%d/%Y")})</h1>
    <p>{df.to_html(index=False)}</p>
    </body></html>
    """
msg_text = MIMEText(html, 'html')
msg.attach(msg_text)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
bananas
  • 133
  • 8
  • are you sure you pasted the sample code correctly? – matszwecja Nov 09 '22 at 13:54
  • 3
    Maybe there are `"""` somewhere else in the code? – muliku Nov 09 '22 at 13:56
  • There are no other """ between the code i sent you. It is a direct copy paste – bananas Nov 09 '22 at 14:16
  • 1
    what you pasted in the first snippet is the correct Python syntax (while a space between the 'f' and quotes is a syntax error ) - are you sure the cells you are putting this in JuPyter are set as Python cells? Or maybe it could be just a highlight bug in the version you are running, and it will work just ok? (I find it very little likely, but it might be the case) – jsbueno Nov 09 '22 at 14:36
  • 1
    @jsbueno you are correct...i kept it the same format and it worked just fine...It just looks wrong in the version I am running. – bananas Nov 09 '22 at 15:46

1 Answers1

2

Making multi-line f-strings is covered here and here, as well as other places. In this example here multi-line f-strings inside a multi-line triple-quoted string work with only the f marking it as an f-string being invoked on the first line. Note though there and here tried to have indenting on the rest of the lines. I found I had to remove the indentation to get it to work.

I sometimes call the triple-quoted string assignments 'docstrings', but they are actually different. For completeness, here using a Python docstring with f-strings is different. This answer here covers fairly well how "Docstrings in Python must be regular string literals."

Wayne
  • 6,607
  • 8
  • 36
  • 93