Skip to main content
 首页 » 编程设计

python之字符串格式化 float %x.yf

2025年01月19日25dudu

我正在通读 Natural Language Processing With Python 并且我遇到了:

count, total = 3205, 9375 
"accuracy for %d words: %2.4f%%" % (total, 100 * count / total) 

我见过 %.4f,但小数点前从未有过整数。玩弄它以下所有打印相同的东西(34.1867):

print('%.4f' %(100*count/total)) 
print('%0.4f' %(100*count/total)) 
print('%1.4f' %(100*count/total)) 
print('%2.4f' %(100*count/total)) 

等等。小数点前的值有什么作用?

请您参考如下方法:

第一个数字指定 minimum field width ,即完整输出的最小长度。

例如,要强制输出至少有 6 个字符且小数点后有 2 个字符,您可以执行以下操作:

'%06.2f' % (3.141592653589793,) 

输出:

003.14