2

查看 djangobook 中的 django 代码:

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)

尝试后,它将偏移量转换为整数,对吗?在'datetime.timedelta(hours=offset)'行中,偏移量用作整数,但在'html = "In %s hour(s)行中,它将是%s。" %(偏移量,dt)'

offset 是一个 %s ,它是一个字符串,对吧?还是我错过了理解?我以为 %s 只能是字符串,不能是整数?

4

3 回答 3

11

%s在其相应的参数上调用该str()方法......(类似于%r调用repr()) - 所以其中任何一个都可以用于任何对象......不像%d%i是相同的),%f例如需要适当的类型。

于 2013-07-21T18:57:56.423 回答
1

In the future, when you're inquisitive about something, fire up the interpreter and explore the simplest case yourself.

>>> a = 1
>>> a
1
>>> 'this is %s string.' % (a)
'this is 1 string.'

Then extrapolate questions from there. Maybe next use an arbitrary object, since an int worked where you thought you needed a str:

>>> from threading import Thread
>>> b = Thread()
>>> b
<Thread(Thread-1, initial)>
>>> 'this is %s string.' % (b)
'this is <Thread(Thread-1, initial)> string.'

This is the general flow of how I explore unexpected results. If you're a doc person, go for it, but I personally never been one for reading the manual; I just don't absorb information that way.

于 2013-07-21T19:08:01.493 回答
1

如果offset是一个整数(在这种特殊情况下,任何对象类型都不是这样),那么您可以使用 , 中的任何一个,%s您将得到相同的结果。%d%r

%d格式化整数以进行显示,%s调用str()参数,%r调用repr()

>>> n = 5
>>> str(n)
'5'
>>> repr(n)
'5'

另请参阅文档

于 2013-07-21T19:02:51.443 回答