布尔在Python中如何格式化为字符串?

问题:布尔在Python中如何格式化为字符串?

我看到我做不到:

"%b %b" % (True, False)

在Python中。我猜%b是b(oolean)。有这样的东西吗?

I see I can’t do:

"%b %b" % (True, False)

in Python. I guessed %b for b(oolean). Is there something like this?


回答 0

>>> print "%r, %r" % (True, False)
True, False

这不是特定于布尔值的- 在参数上%r调用__repr__方法。 %s(对于str)也应该起作用。

>>> print "%r, %r" % (True, False)
True, False

This is not specific to boolean values – %r calls the __repr__ method on the argument. %s (for str) should also work.


回答 1

如果要True False使用:

"%s %s" % (True, False)

因为str(True)'True'str(False)'False'

或者如果您想1 0使用:

"%i %i" % (True, False)

因为int(True)1int(False)0

If you want True False use:

"%s %s" % (True, False)

because str(True) is 'True' and str(False) is 'False'.

or if you want 1 0 use:

"%i %i" % (True, False)

because int(True) is 1 and int(False) is 0.


回答 2

您也可以使用字符串的Formatter类

print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);

这些是结果

True False
True False
1 0
1.000000 0.000000
1.000000e+00 0.000000e+00

某些%-format类型说明符(%r%i)不可用。有关详细信息,请参见格式规范迷你语言

You may also use the Formatter class of string

print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);

These are the results

True False
True False
1 0
1.000000 0.000000
1.000000e+00 0.000000e+00

Some of the %-format type specifiers (%r, %i) are not available. For details see the Format Specification Mini-Language


回答 3

要针对Python-3更新此代码,您可以执行此操作

"{} {}".format(True, False)

但是,如果要实际格式化字符串(例如,添加空格),则会遇到Python将布尔值强制转换为基础C值(即int)的情况,例如

>>> "{:<8} {}".format(True, False)
'1        False'

为了解决这个问题,您可以将True其转换为字符串,例如

>>> "{:<8} {}".format(str(True), False)
'True     False'

To update this for Python-3 you can do this

"{} {}".format(True, False)

However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.

>>> "{:<8} {}".format(True, False)
'1        False'

To get around this you can cast True as a string, e.g.

>>> "{:<8} {}".format(str(True), False)
'True     False'