【问题标题】:How can I format a number for multiple prints in python3.x?如何在 python3.x 中格式化多个打印的数字?
【发布时间】:2015-05-23 18:39:19
【问题描述】:

我希望能够以某种方式格式化一个数字,并让我调用的每个打印函数都以这种方式输出,而不是在每个打印函数中重新格式化它。我只是将其视为一种清理代码的方法。这是一个例子:

给定变量:

weight = mass * conversion_const

并说它的结果超过小数点后 2 位。

那我要打印:

print('The mass of the load is %s Newtons, which is too heavy' %(format(weight, ',.2f')))
print('The mass of the load is %s Newtons, which is too light' %(format(weight, ',.2f')))
print('The mass of the load is %s Newtons, which is just right' %(format(weight, ',.2f')))
print('The mass of the load is %s Newtons, which is wayy to heavy' %(format(weight, ',.2f')))

这只是一个示例,如果我要创建需要这些响应的东西,它将在 if 语句中,但正如您所见,无论哪种方式,我都必须每次都格式化相同的变量。我怎样才能避免这种情况?

【问题讨论】:

  • 为什么不预先计算format(weight, ',.2f')
  • 说实话,没想到这一点,谢谢。

标签: python variables python-3.x printing format


【解决方案1】:

常用格式码的提取方法有很多,例如:

ANSWER_FORMAT = 'The mass of the load is {0:,2f} Newtons, which is {1}'
format_answer = ANSWER_FORMAT.format

print(format_answer(right_weight, 'just_right'))
print(format_answer(heavy_weight, 'too heavy'))

(请注意,新的格式样式如何让生活更轻松。)

【讨论】:

    【解决方案2】:
    weight = "%.2f"%(mass * conversion_const)
    
    print('The mass of the load is %s Newtons, which is too heavy'%(weight))
    print('The mass of the load is %s Newtons, which is too light'%(weight))
    print('The mass of the load is %s Newtons, which is just right'%(weight))
    print('The mass of the load is %s Newtons, which is way to heavy'%(weight))
    

    甚至更好:

    weight = "The mass of the load is %.2f Newtons, which is "%(mass * conversion_const)
    
    print(weight + 'too heavy')
    print(weight + 'too light')
    print(weight + 'just right')
    print(weight + 'way too heavy')
    

    【讨论】:

      【解决方案3】:

      格式化一次,将格式化后的字符串存储在一个变量中,然后使用该变量。

      【讨论】:

      • OP 请求帮助格式化字符串,而您对他的回答是格式化?
      • @IanAuld OP 知道如何格式化字符串,他要求帮助避免冗余,这就是 Stefan 的建议。
      • 无论如何,SO 应该是一个规范的答案存储库。任何未来的读者可能不知道如何格式化字符串,这个答案对他们或其他任何想要学习如何格式化字符串的人都没有用。
      • 如果我可以投票给你的答案,我会的,但我还没有代表。谢谢,虽然这就是我想要的。
      • @IanAuld 我不明白你。每个答案都必须在问题的上下文中看到。这个问题已经显示了如何格式化。我准确地回答了被问到的问题,还有什么可以完成图片。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多