考虑一下:
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/