[英]python string format with negative sign for negative number, but space for positive number
是否有格式代码将 -2.34 格式化为“-2.3”,但将 +2.34 格式化为“2.3”(注意前导空格)? 基本上显示负号,但为正号留出空间。
您可以在float
上尝试format
:
>>> "{: .1f}".format(+2.34)
' 2.3'
>>> "{: .1f}".format(-2.34)
'-2.3'
txt = "The temperature is between {: } and {: } degrees celsius."
print(txt.format(-3, 7))
回答:
The temperature is between -3 and 7 degrees celsius.
使用 f 字符串可以非常简洁地完成:
MYSTR = 2.34
print(f'{MYSTR:{".1f" if MYSTR < 0 else " .1f"}}')
f = lambda i: " %.1f"%i if i > 0 else "%.1f"%i
pos = 2.358
neg = -2.358
print(f(pos)) # " 2.3"
print(f(neg)) # "-2.3"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.