0

I've spent way too long working on this stupidly simple task. At this point I'm just bemused.

I have the following code:

from datetime import datetime
# xyz defined elsewhere in code ... unimportant for this code style question

abc = f"Date and Time: {xyz.strftime('%A, %B %d at %I:%M:%S %p')}"

The last line (abc = ...) is over 80 characters long, so I'm trying to split it across two lines. I've tried the backslash (\), I've tried simply pressing "Enter" to put the code on a new line, and I've tried wrapping the code in parentheses. But each method returns a SyntaxError.

For example, if I type and execute:

abc = f"Date and Time: {xyz.strftime \
    ('%A, %B %d at %I:%M:%S %p')}"

I get the following error: SyntaxError: f-string expression part cannot include a backslash

How can I properly split this single line of code into two lines of code?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Alureon
  • 179
  • 1
  • 3
  • 14
  • 2
    You don't need to mix f-strings and `strftime`. Either `xyz.strftime("Date and Time: %A, %B...")` or `f'{Date and Time: {xyz:%A, %B...}'` will suffice. – chepner Jan 21 '22 at 21:48
  • @chepner I did not know this! The first method works just fine. Thank you! – Alureon Jan 21 '22 at 21:53

1 Answers1

0

I would just extract the variable

t = xyz.strftime('%A, %B %d at %I:%M:%S %p')
abc = f"Date and Time: {t}"
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245