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

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

>>> 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.我知道bool是int的子类,所以True的计算结果为1:

>>> format(True, "d") # shows True in a decimal format
'1'

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

我转向docs for clarification.唯一说的是:

A general convention is that an empty format string ("") produces the same result as if you had called str() on the value. A non-empty format string typically modifies the result.

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

优秀的问题!我相信我有答案。这需要通过C中的Python源代码挖掘,所以忍受我。

首先,格式(obj,format_spec)只是obj .__格式__(format_spec)的语法糖。具体来说,在这种情况下,您必须在abstract.c中查看该功能:

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

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中的一个功能:

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”,这个奥秘已经结束了!

http://stackoverflow.com/questions/23655005/printing-boolean-values-true-false-with-the-format-method-in-python

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:使用Python中的format()方法打印布尔值True/False