Python f-string formatting not working with strftime inline

Viewed 14718

I'm hitting an odd error that I'm trying to understand. Doing some general code cleanup and converting all string formatting to f-strings. This is on Python 3.6.6

This code does not work:

from datetime import date
print(f'Updated {date.today().strftime('%m/%d/%Y')}')

  File "<stdin>", line 1
    print(f'Updated {date.today().strftime('%m/%d/%Y')}')
                                               ^
SyntaxError: invalid syntax

However, this (functionally the same) does work:

from datetime import date
d = date.today().strftime('%m/%d/%Y')
print(f'Updated {d}')

Updated 11/12/2018

I feel like I'm probably missing something obvious, and am fine with the second iteration, but I want to understand what's happening here.

4 Answers
print(f'Updated {date.today().strftime("%m/%d/%Y")}')

Your code was prematurely ending the string definition.

if string is part of another string you need to use double quote in one of them

(f"updated {date.today().strftime('%D')}") # %m/%d/%y can also be written %D

Strangely this has not been proposed:

print(date.today().strftime("Updated: %m/%d/%Y"))
Related