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