Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can %s be an integer? *Python code*

Tags:

python

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?

like image 843
user216485 Avatar asked Jan 29 '26 12:01

user216485


2 Answers

%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.

like image 51
Jon Clements Avatar answered Jan 31 '26 00:01

Jon Clements


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.

like image 31
alecxe Avatar answered Jan 31 '26 01:01

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!