将布尔值转换为字符串的等效方法是什么?是否有类似于 str.format
函数的方法?
>>> "%5s" % True
' True'
>>> "%5s" % False
'False'
请注意
' True'
中的空格。这总是使' True'和' False'的长度相同。我已经查看了此帖子中的方法:How are booleans formatted in Strings in Python?。它们都无法做到相同的事情。
将布尔值转换为字符串的等效方法是什么?是否有类似于 str.format
函数的方法?
>>> "%5s" % True
' True'
>>> "%5s" % False
'False'
' True'
中的空格。这总是使' True'和' False'的长度相同。您可以使用类型转换标志来完成所需操作:
'{:_>5}'.format(True) # Oh no! it's '____1'
'{!s:_>5}'.format(True) # Now we get '_True'
!s
。我使用下划线更清楚地显示填充。它也适用于f-strings:f'{True:_>5}' # '____1'
f'{True!s:_>5}' # '_True'
6.1.3. Format String Syntax
[...]
The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the
__format__()
method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling__format__()
, the normal formatting logic is bypassed.Three conversion flags are currently supported:
'!s'
which callsstr()
on the value,'!r'
which callsrepr()
and'!a'
which callsascii()
.Some examples:
"Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first
str()
函数。更多相关信息在这里。x = str(True)
y = False
print( type(x) )
<class 'str'> # This is a string
print( type(y) )
<class 'bool'> # This is a boolean
"{:>5}".format(str(True))
可以正常工作。
输出与"%5s" % True
完全相同,即' True'
。"{:>5}".format(str(bool_value))
的长度始终为5,无论bool_value
是True
还是False
。"{:6}".format(str(True))
输出'True '
。不太确定我是否正确理解了这个想法,但是如果某个变量 x 的结果为真或假,您可以写成 str(x);否则的话,抱歉,请尝试更详细地解释问题 Q。