控制台打印输出的美化

Beautification of the print output of the console

我在控制台中有一个输出。不幸的是,这些文本的长度不同,因此看起来很不一样。是否有一个选项可以将文本写在彼此下面,而不管它们前面有多少个字符,以便输出看起来像我想要的样子?

我不想为此使用其他库。

print(65 * '_')
print('algorithm\t\t\tsil\t\tdbs')

results =  ['Agglomerative Clustering', 0.8665, 0.4200]
formatter_result = ("{:9s}\t\t{:.4f}\t{:.4f}")
print(formatter_result.format(*results))
    
results = ['k-Means', 0.9865, 0.1200]
formatter_result = ("{:9s}\t\t{:.4f}\t{:.4f}")
print(formatter_result.format(*results))

print(65 * '_')

我有什么

_________________________________________________________________
algorithm           sil     dbs
Agglomerative Clustering        0.8665  0.4200
k-Means         0.9865  0.1200
_________________________________________________________________

我想要的

_________________________________________________________________
algorithm                    sil        dbs
Agglomerative Clustering     0.8665     0.4200
k-Means                      0.9865     0.1200
_________________________________________________________________

我看了 Printing Lists as Tabular Data 并试了一下,但对我不起作用

print(65 * '_')

heading = ['algorithm', 'sil', 'dbs']
result1 =  ['Agglomerative Clustering', 0.8665, 0.4200]
result2 = ['k-Means', 0.9865, 0.1200]
ab = np.array([heading, result1, result2])
for row in ab:
    print("{: >20} {: >20} {: >20}".format(*row))
    



print(65 * '_')
_________________________________________________________________
           algorithm                  sil                  dbs
Agglomerative Clustering               0.8665                 0.42
             k-Means               0.9865                 0.12
_________________________________________________________________

你好所以你必须删除一些 \t 因为它们会创建标签,你可以一个一个地删除它们以找到你喜欢的

打印('for example, this is a tab \t\t\t there is going to be space between them')

打印('for example, there is no tab here and it is going to be next to each other')

您可以使用 {:<20},这意味着 20 个空格左对齐。还有 {:^20} - 居中对齐和 {:>20}- 右对齐。

将其与 float 符号组合,例如.4f 只需添加:{:<20.4f}

试试这个:

print(65 * "_")
formatter_result = "{:<35} {:<20} {:<20}"
formatter_result_f = "{:<35} {:<20.4f} {:<20.4f}"
print(formatter_result.format(*["algorithm", "sil", "dbs"]))
results = ["Agglomerative Clustering", 0.8665, 0.4200]
print(formatter_result_f.format(*results))
results = ["k-Means", 0.9865, 0.1200]
print(formatter_result_f.format(*results))
print(65 * "_")

结果:

_________________________________________________________________
algorithm                           sil                  dbs                 
Agglomerative Clustering            0.8665               0.4200              
k-Means                             0.9865               0.1200              
_________________________________________________________________