[英]how to format integers so that it prints spaces before it if there are not three number
I want to print some sequence of number in a specific format.我想以特定格式打印一些数字序列。 Like if there are 3 digits it will print the integer but if there are not 3 digits for example if there are two digits or one digit then it will make up spaces.就像如果有 3 位数字,它将打印 integer 但如果没有 3 位数字,例如如果有两位数字或一位数字,那么它将构成空格。 For example:例如:
__3 bench __3 长凳
_55 pencils _55 支铅笔
675 pens 675支笔
I wanted to how can I format this.我想如何格式化它。 the numbers are always integers.数字总是整数。
for key, value in dict.items():
print(f'{key:} {value}')
something like this by giving width
to your paramater to print:通过给你的参数提供width
来打印这样的东西:
for key, value in dict.items():
print (f'{key:>3} {value}')
width = 3
for key, value in dict.items():
print (f'{key:>{width}} {value}')
you can replace 3 with the maximum number of digits you might have in your data or even pass it dynamically:您可以将 3 替换为数据中可能包含的最大位数,甚至动态传递它:
width = 3 for key, value in dict.items(): print (f'{key:>{width}} {value}')
You might use .rjust
method after converting int
to str
.将int
转换为str
后,您可以使用.rjust
方法。 Consider following example考虑以下示例
benches = 3
pencils = 55
pens = 675
print(str(benches).rjust(3),"benches")
print(str(pencils).rjust(3),"pencils")
print(str(pens).rjust(3),"pens")
output output
3 benches
55 pencils
675 pens
Similar methods exists named .ljust
(justing to left) and .center
存在类似的方法,名为.ljust
(左对齐)和.center
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.