python - 在字符串格式中调用类方法

标签 python string format

考虑一下:

from datetime import datetime

now = datetime.now() 
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22

'{0.strftime("%p")}'.format(now)
# gives
# AttributeError: 'datetime.datetime' object has no attribute 'strftime("%p")'

这似乎意味着我不能在格式中调用类方法(我猜这就是 strftime 的意思)。
对此有什么解决方法(假设我需要在字符串中调用方法,并继续使用格式)?

最佳答案

你可以这样做。

>>> from datetime import datetime
>>> now = datetime.now()
>>> '{0:%p}'.format(now)
'PM'
这也适用于 f -字符串也是。
>>> f"{now:%p}"
'PM'

关于python - 在字符串格式中调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65846671/

相关文章:

c++ - 字符串到 LPCTSTR

PHP IntlDateFormatter 格式返回错误的日期

video - 如何将视频编码为 h264?

python - pathlib 的 `glob` 方法的顺序在运行之间是否一致?

python - 在数组中找到最 "empty"的地方

string - 如何在go中将unicode字节数组转换为普通字符串

c - fputs 是否比格式 ("%s"更有效,..)?

python - 在 Python 中,我可以隐藏基类的成员吗?

Python 日志记录与性能

c++ - 初始化 std::string 的不同方法之间的区别