【问题标题】:How to control length of the result of string.format(bool_value) in Python?如何在 Python 中控制 string.format(bool_value) 结果的长度?
【发布时间】:2016-08-03 01:30:40
【问题描述】:
【问题讨论】:
标签:
python
string
formatting
【解决方案1】:
你可以使用类型转换标志来做你想做的事:
'{:_>5}'.format(True) # Oh no! it's '____1'
'{!s:_>5}'.format(True) # Now we get '_True'
注意!s。我使用下划线更清楚地显示填充。
相关文档:
[...]
conversion 字段在格式化之前会导致类型强制。通常,格式化值的工作是由值本身的__format__() 方法完成的。但是,在某些情况下,需要强制将类型格式化为字符串,从而覆盖其自己的格式化定义。通过在调用__format__()之前将值转换为字符串,绕过了正常的格式化逻辑。
目前支持三个转换标志:'!s' 调用 str() 值,'!r' 调用 repr() 和 '!a' 调用 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
【解决方案2】:
您可以使用str() 函数。更多相关信息here。
这里有一些例子:
x = str(True)
y = False
print( type(x) )
<class 'str'> # This is a string
print( type(y) )
<class 'bool'> # This is a boolean
【解决方案3】:
我发现"{:>5}".format(str(True)) 工作正常。
输出与"%5s" % True完全相同,即' True'。
所以"{:>5}".format(str(bool_value))的长度总是5,不管bool_value是True还是False。
当然,您可以根据需要更改长度或对齐方向。例如。 "{:6}".format(str(True)) 输出'True '。
【解决方案4】:
不确定我的想法是否正确,但如果某个变量 x 的结果是 True 或 False,你可以写 str(x);如果不是这样,抱歉,请尝试更详细地解释 Q