首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python中使用format()方法打印布尔值True/False

在Python中使用format()方法打印布尔值True/False
EN

Stack Overflow用户
提问于 2014-05-14 20:38:00
回答 1查看 19.8K关注 0票数 22

我试着打印一个布尔表达式的真值表。在这样做的时候,我偶然发现了以下几点:

代码语言:javascript
复制
>>> format(True, "") # shows True in a string representation, same as str(True)
'True'
>>> format(True, "^") # centers True in the middle of the output string
'1'

只要我指定了格式说明符,format()就会将True转换为1。我知道boolint的子类,所以True的计算结果是1

代码语言:javascript
复制
>>> format(True, "d") # shows True in a decimal format
'1'

但是为什么在第一个示例中使用格式说明符将'True'更改为1呢?

我转向docs for clarification。上面只说了一句话:

一般约定是,空格式字符串("")产生的结果与您对该值调用str()时产生的结果相同。非空格式字符串通常会修改结果。

因此,当您使用格式说明符时,字符串会被修改。但是如果只指定了对齐运算符(例如^),为什么要从True更改为1呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-15 07:36:06

问得好!我相信我有答案。这需要深入研究用C编写的Python源代码,所以请耐心等待。

首先,format(obj, format_spec)只是obj.__format__(format_spec)的语法糖。对于发生这种情况的具体位置,您必须在函数中查看abstract.c

代码语言:javascript
复制
PyObject *
PyObject_Format(PyObject* obj, PyObject *format_spec)
{
    PyObject *empty = NULL;
    PyObject *result = NULL;

    ...

    if (PyInstance_Check(obj)) {
        /* We're an instance of a classic class */
HERE -> PyObject *bound_method = PyObject_GetAttrString(obj, "__format__");
        if (bound_method != NULL) {
            result = PyObject_CallFunctionObjArgs(bound_method,
                                                  format_spec,
                                                  NULL);

    ...
}

要找到确切的调用,我们必须在intobject.c中查找

代码语言:javascript
复制
static PyObject *
int__format__(PyObject *self, PyObject *args)
{
    PyObject *format_spec;

    ...

    return _PyInt_FormatAdvanced(self,
                     ^           PyBytes_AS_STRING(format_spec),
                     |           PyBytes_GET_SIZE(format_spec));
               LET'S FIND THIS
    ...
}

_PyInt_FormatAdvanced实际上被定义为formatter_string.c中的宏,作为formatter.h中的函数

代码语言:javascript
复制
static PyObject*
format_int_or_long(PyObject* obj,
               STRINGLIB_CHAR *format_spec,
           Py_ssize_t format_spec_len,
           IntOrLongToString tostring)
{
    PyObject *result = NULL;
    PyObject *tmp = NULL;
    InternalFormatSpec format;

    /* check for the special case of zero length format spec, make
       it equivalent to str(obj) */
    if (format_spec_len == 0) {
        result = STRINGLIB_TOSTR(obj);   <- EXPLICIT CAST ALERT!
        goto done;
    }

    ... // Otherwise, format the object as if it were an integer
}

这就是你的答案。一个简单的检查format_spec_len是否为0,如果是,将obj转换为字符串。正如您所熟知的,str(True)就是'True',谜团就此结束!

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23655005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档