是否有格式代码将 -2.34 格式化为“-2.3”,但将 +2.34 格式化为“2.3”(注意前导空格)?基本上显示负号,但为正号留出空间。
小智 7
txt = "The temperature is between {: } and {: } degrees celsius."
print(txt.format(-3, 7))
Run Code Online (Sandbox Code Playgroud)
回答 :
The temperature is between -3 and 7 degrees celsius.
Run Code Online (Sandbox Code Playgroud)
您可以format尝试float:
>>> "{: .1f}".format(+2.34)
' 2.3'
>>> "{: .1f}".format(-2.34)
'-2.3'
Run Code Online (Sandbox Code Playgroud)