Python f 字符串格式不适用于 strftime 内联

Python f-string formatting not working with strftime inline

我正在尝试理解一个奇怪的错误。进行一些常规代码清理并将所有字符串格式转换为 f 字符串。这是在 Python 3.6.6

此代码无效:

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

但是,这个(功能相同)确实有效:

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

Updated 11/12/2018

我觉得我可能遗漏了一些明显的东西,第二次迭代没问题,但我想了解这里发生了什么。

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

您的代码过早地结束了字符串定义。

如果字符串是另一个字符串的一部分,您需要在其中一个字符串中使用双引号

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

有一种原生方式:

print(f'Updated {date.today():%m/%d/%Y}')

更多相关信息:

奇怪的是这个没有被提议:

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