简体   繁体   English

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

[英]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}')

output: output:
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.

相关问题 如何编写打印三个数字中最大数字的 function - How to write a function that prints the highest number out of three numbers “如何修改以下程序,使其以特定格式打印?” - “How can I modify the below program so it prints in a specific format?” 我如何修改此函数,以便使用特定算法输出1与其参数之间的整数? - How do I amend this function so that it prints integers between 1 and its parameter, using a particular algorithm? 如何在python3.x中格式化多个打印的数字? - How can I format a number for multiple prints in python3.x? 我该如何格式化,所以在 python 中没有空格 - How do I format this so no spaces are made in python 如何编写程序打印出 1 和给定数字之间的所有正整数,并在范围的两端之间交替? - How to write the program that prints out all positive integers between 1 and given number , alternating between the two ends of the range? 格式字符串 - 每三位数之间的空格 - Format string - spaces between every three digit 如何打印前面有一定数量空格的整数? - How do I print an integer with a set number of spaces before it? 如何修复此代码,使其打印一串字母,其中一个位置被相应的输入数字替换? - How to fix this code so that it prints a string of letters with one of the positions replaced by a corresponding inputted number? 编写一个程序,比较三个数字并打印最大的奇数 - Write a program that compares the three numbers and prints the largest odd number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM