繁体   English   中英

python 字符串格式,负数用负号,正数用空格

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM