如何在Python中控制string.format(bool_value)结果的长度?

4

将布尔值转换为字符串的等效方法是什么?是否有类似于 str.format 函数的方法?

>>> "%5s" % True
' True'

>>> "%5s" % False
'False'

请注意' True'中的空格。这总是使' True'和' False'的长度相同。
我已经查看了此帖子中的方法:How are booleans formatted in Strings in Python?。它们都无法做到相同的事情。
4个回答

5

您可以使用类型转换标志来完成所需操作:

'{:_>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 calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().

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

1
你可以使用str()函数。更多相关信息在这里
以下是一些例子:
x = str(True)
y = False

print( type(x) )
<class 'str'>   # This is a string

print( type(y) )
<class 'bool'>  # This is a boolean

1
我发现"{:>5}".format(str(True))可以正常工作。 输出与"%5s" % True完全相同,即' True'
因此,"{:>5}".format(str(bool_value))的长度始终为5,无论bool_valueTrue还是False
当然,您可以根据需要更改长度或对齐方向。例如:"{:6}".format(str(True))输出'True '

0

不太确定我是否正确理解了这个想法,但是如果某个变量 x 的结果为真或假,您可以写成 str(x);否则的话,抱歉,请尝试更详细地解释问题 Q。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接