【问题标题】:How do I concatenate strings of rounded numbers python?如何连接四舍五入的数字字符串python?
【发布时间】:2020-07-18 02:11:03
【问题描述】:

我无法找出我在 python 中连接字符串的方式的错误。

我们的目标是将数字格式化成一个字符串,我可以以一致的长度打印它。

我写了以下代码:

def numPrint(number,roundplace):
    num = round(number, roundplace)
    if num > 0:
        output = ('+' + str(num))
    elif num < 0:
        output = (str(num))
    else:
        output = (' 0.' + '0' * roundplace)    

    if len(output) < (3 + roundplace):
        output2 = (output + '0')
    else:
        output2 = output

    return output2

print(numPrint(0.001, 3))
print(numPrint(0, 3))
print(numPrint(-0.0019, 3))
print(numPrint(-0.01, 3))
print(numPrint(0.1, 3))

我希望它打印出来:

+0.001
 0.000
-0.002
-0.010
+0.100

但是,我得到了

+0.001
 0.000
-0.002
-0.010
+0.10

如何将“0”添加到最后一个以使其工作?

【问题讨论】:

  • 为什么不使用格式选项? eg:print('{:.3f}'.format(0.1)) 3表示保留小数点后3位。

标签: python python-3.x string concatenation string-concatenation


【解决方案1】:

您只是忘记将output2 的零相乘:

if len(output) < (3 + roundplace):
    output2 = (output + ('0'*(3 + roundplace - len(output))))
else:
    output2 = output

或者如果你不介意使用内置函数:

output2 = output.ljust(3 + roundplace, '0')

【讨论】:

    【解决方案2】:

    如果您只想显示数字,可以使用字符串格式。

    def format_number(number, minimum_digits=1, decimal_places=2):
        format_string = '{{: {}.{}f}}'.format(minimum_digits, decimal_places)
        result = format_string.format(number)
        if number:
            result = result.replace(' ', '+', 1)  # Technically you can use '+' above but your desired output requires zero to have no sign
        return result
    
    print(format_number(0.001, minimum_digits=1, decimal_places=3))
    print(format_number(0, minimum_digits=1, decimal_places=3))
    print(format_number(-0.0019, minimum_digits=1, decimal_places=3))
    print(format_number(-0.01, minimum_digits=1, decimal_places=3))
    print(format_number(0.1, minimum_digits=1, decimal_places=3))
    
    +0.001
     0.000
    -0.002
    -0.010
    +0.100
    

    【讨论】:

      【解决方案3】:

      试试这个:

      
      def num_print(number, roundplace):
          sign = '+' if number != 0 else ' '
          output = '{num:{sign}.{rp}f}'.format(num=number, sign=sign, rp=roundplace) # python3
      #     output = f'{number:{sign}.{roundplace}f}' # python 3.6 +
          return output
      
      
      +0.001
       0.000
      -0.002
      -0.010
      +0.100
      

      【讨论】:

        【解决方案4】:

        试试.format()字符串方法,真的好用好用。

        def numPrint(number,roundPlace):
           return "{{:+.{}f}}".format(roundPlace).format(number)
        

        【讨论】:

        • 恕我直言,这是最好的答案。
        • 你可以简单一点:return "{:+.{}f}".format(number, roundPlace).
        【解决方案5】:

        您可以像这样使用内置格式功能:

        print("{:+.4f}".format(0.09))

        在此处查看有关格式规范的更多详细信息:

        https://docs.python.org/3.4/library/string.html#formatexamples

        【讨论】:

          【解决方案6】:

          这将起作用:

          def numPrint(number,roundplace):
              num = round(number, roundplace)
              if num > 0:
                  output = ('+' + str(num))
              elif num < 0:
                  output = (str(num))
              else:
                  output = (' 0.' + '0' * roundplace)    
          
              while len(output) < (3 + roundplace): # previously you stopped after adding one trailing 0
                  output = (output + '0')
          
              return output
          
          print(numPrint(0.001, 3))
          print(numPrint(0, 3))
          print(numPrint(-0.0019, 3))
          print(numPrint(-0.01, 3))
          print(numPrint(0.1, 3))
          

          【讨论】:

            【解决方案7】:

            对于 Python 3.6+,您可以使用 f-string:

            def num_print(number, round_place):
                return f"{number:{'+' if number else ' '}.{round_place}f}"
            

            (我故意将您的函数名称及其第二个参数从 numPrintroundPlace 更改为 num_printround_place 以与 PEP 8 - Style Guide: Function and Variable Names 保持一致。)

            【讨论】:

              猜你喜欢
              • 2015-11-12
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-01-22
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多