python字符串格式,负号表示负数,但空格表示正数

jf3*_*328 10 python

是否有格式代码将 -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)


Har*_*ani 5

您可以format尝试float

>>> "{: .1f}".format(+2.34)
' 2.3'
>>> "{: .1f}".format(-2.34)
'-2.3'
Run Code Online (Sandbox Code Playgroud)