[英]How to pad string based on digits in a number?
Suppose I have an arbitrary number: 假设我有一个任意数字:
my_number = 898
I want to create a loop that counts up to that number, using a padding for the current count equal to the digits of that maximum number. 我想创建一个计数到该数字的循环,使用当前计数的填充等于该最大数字的位数。 In other words, if
my_number
is 5 digits long, then when the count is at 1 it should read ----1
, where each -
is one space in the padding. 换句话说,如果
my_number
为5位数字,则当计数为1时,它应读为----1
,其中每个-
是填充中的一个空格。 Likewise, if we're at number 500 then it should be padded like so: --500
. 同样,如果我们的数字是500,则应像这样填充
--500
。 Example loop: 示例循环:
for i in range(my_number):
print( '{}: Current Number'.format(i) )
I hope I'm clear. 我希望我清楚。 I just don't know what the 'pythonic' way of doing this would be.
我只是不知道这样做的“ pythonic”方式是什么。 I imagine there is some clean way of doing this in python but I can't help but think of a cumbersome solution that would require several lines of code.
我想在python中有一些干净的方法可以做到这一点,但我不禁想到一个麻烦的解决方案,它需要几行代码。
You could use right-aligned format
specifier for it: 您可以使用右对齐
format
说明符 :
In [23]: num = 15
In [24]: for x in range(num):
print("{0:>{1}}".format(x, len(str(num))))
....:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Something like this? 像这样吗
>>> my_number = 15
>>> for i in range(my_number):
... strung = str(i)
... print('-'*(len(str(my_number))-len(strung))+strung) # If you want spaces instead of dashes, do print(' '*(len(.......
...
-0
-1
-2
-3
-4
-5
-6
-7
-8
-9
10
11
12
13
14
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.