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

Syr*_*jor 4 python string formatting

str.format将布尔值转换为字符串的等效方法是什么?

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

>>> "%5s" % False
'False'
Run Code Online (Sandbox Code Playgroud)

请注意 中的空格' True'。这始终使“True”和“False”的长度相同。

我已经检查了这篇文章中的方法:

Python 中的字符串中的布尔值是如何格式化的?

他们中没有人能做同样的事情。

Mic*_*ael 5

您可以使用类型转换标志来执行您想要的操作:

'{:_>5}'.format(True)   # Oh no! it's '____1'
'{!s:_>5}'.format(True) # Now we get  '_True'
Run Code Online (Sandbox Code Playgroud)

请注意!s. 我使用下划线来更清楚地显示填充。它也适用于 f 字符串:

f'{True:_>5}'   # '____1'
f'{True!s:_>5}' # '_True'
Run Code Online (Sandbox Code Playgroud)

相关文档:

6.1.3. 格式化字符串语法

[...]

转换字段在格式化之前导致类型强制。通常,格式化值的工作是通过__format__()值本身的方法完成的。但是,在某些情况下,需要强制将类型格式化为字符串,从而覆盖其自身的格式化定义。通过在调用之前将值转换为字符串__format__(),可以绕过正常的格式化逻辑。

当前支持三种转换标志:'!s'which 调用str()value、'!r'which 调用repr()'!a'which 调用ascii()

一些例子:

"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
Run Code Online (Sandbox Code Playgroud)