如果没有三个数字,如何格式化整数以便在它之前打印空格

how to format integers so that it prints spaces before it if there are not three number

我想以特定格式打印一些数字序列。就像如果有 3 位数字它会打印整数但是如果没有 3 位数字例如如果有两位数或一位数那么它将弥补空间。例如:
__3 板凳
_55支铅笔
675 支笔
我想如何格式化它。数字总是整数。

 for key, value in dict.items():
        print(f'{key:} {value}')

通过给你的参数 width 来打印这样的东西:

for key, value in dict.items():
    print (f'{key:>3} {value}')

输出:

>
  3 bench
 45 pencils
675 pens

您可以将 3 替换为数据中可能包含的最大位数,甚至可以动态传递:

width = 3
for key, value in dict.items():
    print (f'{key:>{width}} {value}')

int转换为str后,您可能会使用.rjust方法。考虑以下示例

benches = 3
pencils = 55
pens = 675
print(str(benches).rjust(3),"benches")
print(str(pencils).rjust(3),"pencils")
print(str(pens).rjust(3),"pens")

输出

  3 benches
 55 pencils
675 pens

存在名为 .ljust(刚好向左)和 .center

的类似方法