等效的方法是什么str.format
将布尔值转换为字符串的函数?
>>> "%5s" % True
' True'
>>> "%5s" % False
'False'
请注意其中的空格' True'
。这始终使“True”和“False”的长度相同。
我已经检查了这篇文章中的方法:
Python 中的字符串中的布尔值是如何格式化的? https://stackoverflow.com/questions/2259228/how-are-booleans-formatted-in-strings-in-python
他们中没有人能做同样的事情。
您可以使用类型转换标志来执行您想要的操作:
'{:_>5}'.format(True) # Oh no! it's '____1'
'{!s:_>5}'.format(True) # Now we get '_True'
请注意!s
。我使用下划线来更清楚地显示填充。它也适用于 f 字符串:
f'{True:_>5}' # '____1'
f'{True!s:_>5}' # '_True'
相关文档:
6.1.3. 格式化字符串语法 https://docs.python.org/3/library/string.html#format-string-syntax
[...]
The 转换字段在格式化之前会导致类型强制。通常,格式化值的工作是由__format__() https://docs.python.org/3/reference/datamodel.html#object.__format__值本身的方法。但是,在某些情况下,需要强制将类型格式化为字符串,从而覆盖其自身的格式化定义。在调用之前将值转换为字符串__format__() https://docs.python.org/3/reference/datamodel.html#object.__format__,绕过正常的格式化逻辑。
目前支持三个转换标志:'!s'
哪个调用str() https://docs.python.org/3/library/stdtypes.html#str就价值而言,'!r'
哪个调用repr() https://docs.python.org/3/library/functions.html#repr and '!a'
哪个调用ascii() https://docs.python.org/3/library/functions.html#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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)