Skip to main content
 首页 » 编程设计

python之如何打印变量之间的空格

2025年05月04日10lonelyxmas

我需要打印一行

Device       Size     Calculated       Status 

我是这样做的

dev =  "Device" 
size = "Size" 
calc = "Calculated" 
stat = "Status" 
print "%s%(15-x1)%s%(15-x2)%s%(15-x3)%s" % (dev, size, calc, stat) 

x1 x2 x3 然后是空格的个数。 但我得到一个错误:

File "<stdin>", line 1, in <module> 
TypeError: format requires a mapping 

这个命令怎么写?

请您参考如下方法:

它比你想象的要简单:

 print "%-15s %-15s %-15s %-15s" % (dev, size, calc, stat) 

15 说“这个字符串在输出中需要 15 个字符宽。” - 表示:“如有必要,请在右侧用空格填充它。”如果没有 -,值将在左侧填充。