python - 在 Python 中使用 format() 方法打印 boolean 值 True/False

标签 python python-2.7 boolean string-formatting string.format

我试图打印 boolean 表达式的真值表。在执行此操作时,我偶然发现了以下内容:

>>> 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()转换 True1 .我知道boolint 的子类,所以 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 源代码,所以请耐心等待。

首先,format(obj, format_spec) 只是 obj.__format__(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',谜底结束!

关于python - 在 Python 中使用 format() 方法打印 boolean 值 True/False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23655005/

相关文章:

python - 如何将行转换为 Pandas 中的列?

python - 在 url.py 中包含关键字在没有 app_name 的情况下不起作用(Django 2.0)

python - 查找列表中第一个正元素的索引 - python

python-2.7 - 即使已安装,也没有名为 gevent 的模块

mysql - 用于存储 boolean 值的 MySQL 数据类型

mysql - 不带引号的 boolean 插入 - Liquibase over MySQL

python - 使用 pandas 对数据进行排序 - 根据其他列中的值对第一列进行排序

python - 并行运行 Python Trainer 脚本

Python:接受 unicode 字符串作为 doctests 中的常规字符串

javascript - 确认匹配的结束 boolean 问题 (JavaScript)