Looking at this django code from the djangobook:
from django.http import Http404, HttpResponse
import datetime
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
return HttpResponse(html)
after the try, it converts offset into an integer, right? and in the line 'datetime.timedelta(hours=offset)', offset is used as an integer, but in the line 'html = "In %s hour(s), it will be %s." % (offset, dt)'
offset is a %s which is a string, right? Or am I miss understanding? I thought %s only can be a string, not an integer?
%s calls the str() method on its corresponding argument... (similar to %r calls repr()) - so either of those can be used for any object... Unlike %d (%i is the same) and %f for instance which will require appropriate types.
If offset is an integer (in this particular case, it's not true for any object type), then you can use any of %s, %d, %r and you'll get the same result.
%d formats an integer number for display, %s calls str() on an argument, %r calls repr():
>>> n = 5
>>> str(n)
'5'
>>> repr(n)
'5'
Also see documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With