【问题标题】: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
【问题描述】:

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

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

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

请注意' True' 中的空格。这总是使 'True' 和 'False' 的长度相同。

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

How are booleans formatted in Strings in Python?

他们都不能做同样的事情。

【问题讨论】:

    标签: python string formatting


    【解决方案1】:

    你可以使用类型转换标志来做你想做的事:

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

    注意!s。我使用下划线更清楚地显示填充。

    相关文档:

    6.1.3。 Format String Syntax

    [...]

    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】:

        我发现"{:&gt;5}".format(str(True)) 工作正常。 输出与"%5s" % True完全相同,即' True'

        所以"{:&gt;5}".format(str(bool_value))的长度总是5,不管bool_valueTrue还是False

        当然,您可以根据需要更改长度或对齐方向。例如。 "{:6}".format(str(True)) 输出'True '

        【讨论】:

          【解决方案4】:

          不确定我的想法是否正确,但如果某个变量 x 的结果是 True 或 False,你可以写 str(x);如果不是这样,抱歉,请尝试更详细地解释 Q

          【讨论】:

            猜你喜欢
            • 2021-12-22
            • 1970-01-01
            • 1970-01-01
            • 2015-05-24
            • 1970-01-01
            • 1970-01-01
            • 2022-11-14
            • 2018-10-07
            • 1970-01-01
            相关资源
            最近更新 更多