Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

python - Calling class method inside string format

Consider this:

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")'

This seems to imply that I can't call a class method inside the format (I guess that's what strftime is).

What's a workaround for this (assuming I need to call the method inside the string, and keep using a format) ?

question from:https://stackoverflow.com/questions/65846671/calling-class-method-inside-string-format

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could do this.

>>> from datetime import datetime
>>> now = datetime.now()
>>> '{0:%p}'.format(now)
'PM'

This will also work with f-strings too.

>>> f"{now:%p}"
'PM'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...