【问题标题】:Format a number as a string将数字格式化为字符串
【发布时间】:2010-10-16 13:08:09
【问题描述】:

如何将数字格式化为字符串,以使其前面有多个空格?我希望较短的数字 5 在其前面有足够的空格,以便空格加上 5 的长度与 52500 相同。下面的过程有效,但是有内置的方法吗?

a = str(52500)
b = str(5)
lengthDiff = len(a) - len(b)
formatted = '%s/%s' % (' '*lengthDiff + b, a)
# formatted looks like:'     5/52500'

【问题讨论】:

    标签: python string integer format


    【解决方案1】:

    Format operator:

    >>> "%10d" % 5
    '         5'
    >>> 
    

    使用*规范,字段长度可以是一个参数:

    >>> "%*d" % (10,5)
    '         5'
    >>> 
    

    【讨论】:

    • 这正是我所需要的。
    【解决方案2】:

    '%*s/%s' % (len(str(a)), b, a)

    【讨论】:

      【解决方案3】:

      您可以只使用%*d 格式化程序来指定宽度。 int(math.ceil(math.log(x, 10))) 会给你位数。 * 修饰符使用一个数字,该数字是一个整数,表示要间隔多少个空格。因此,通过执行'%*d' % (width, num)`,您可以指定宽度并呈现数字,而无需任何进一步的 python 字符串操作。

      这是一个使用 math.log 确定“outof”数字长度的解决方案。

      import math
      num = 5
      outof = 52500
      formatted = '%*d/%d' % (int(math.ceil(math.log(outof, 10))), num, outof)
      

      另一种解决方案是将 outof 数字转换为字符串并使用 len(),如果您愿意,可以这样做:

      num = 5
      outof = 52500
      formatted = '%*d/%d' % (len(str(outof)), num, outof)
      

      【讨论】:

      • len(str(x)) 在我的系统上大约快两倍。它也更容易阅读:-)
      • 是的,但前提是您知道等式的哪一边较长。
      • math.ceil(math.log(x, 10)) 给出 10 次幂的错误结果。
      • 啊有趣。这就是为什么您不应该对单个值进行测试,而是在边缘情况下进行测试。
      【解决方案4】:

      String Formatting Operations:

      s = '%5i' % (5,)
      

      您仍然必须通过包含最大长度来动态构建格式化字符串:

      fmt = '%%%ii' % (len('52500'),)
      s = fmt % (5,)
      

      【讨论】:

        【解决方案5】:

        不确定你到底在追求什么,但这看起来很接近:

        >>> n = 50
        >>> print "%5d" % n
           50
        

        如果您想更有活力,请使用rjust

        >>> big_number = 52500
        >>> n = 50
        >>> print ("%d" % n).rjust(len(str(52500)))
           50
        

        甚至:

        >>> n = 50
        >>> width = str(len(str(52500)))
        >>> ('%' + width + 'd') % n
        '   50'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-09
          • 1970-01-01
          • 1970-01-01
          • 2014-03-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多