簡體   English   中英

使用f-strings python格式化具有相同寬度的數字

[英]Formatting numbers with same width using f-strings python

我想使用f-strings格式化具有相同寬度的數字數組。 數字可以是正數也可以是負數。

最低工作示例

import numpy as np  
arr = np.random.rand(10) - 0.5 
for num in arr:
    print(f"{num:0.4f}")

結果是

0.0647
-0.2608
-0.2724
0.2642
0.0429
0.1461
-0.3285
-0.3914

由於負號,數字不會以相同的寬度打印出來,這很煩人。 如何使用f-string獲得相同的寬度?

我能想到的一種方法是將數字轉換為字符串並打印字符串。 但是有更好的方法嗎?

for num in a: 
    str_ = f"{num:0.4f}" 
    print(f"{str_:>10}")

在格式化字符串之前使用空格:

>>> f"{5: 0.4f}"
' 5.0000'
>>> f"{-5: 0.4f}"
'-5.0000'

或加號( + )強制顯示所有符號:

>>> f"{5:+0.4f}"
'+5.0000'

您可以使用符號 格式選項:

>>> import numpy as np
>>> arr = np.random.rand(10) - 0.5
>>> for num in arr:
...     print(f'{num: .4f}')  # note the leading space in the format specifier
...
 0.1715
 0.2838
-0.4955
 0.4053
-0.3658
-0.2097
 0.4535
-0.3285
-0.2264
-0.0057

引用文檔:

sign選項僅對數字類型有效,可以是以下之一:

 Option Meaning '+' indicates that a sign should be used for both positive as well as negative numbers. '-' indicates that a sign should be used only for negative numbers (this is the default behavior). space indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers. 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM