Jakube
Jakube

Reputation: 3575

format numbers with variable length

I have a bunch of numbers in a list and want to print them in a pretty way, so that they are aligned on the right side.

numbers = [192829, 88288, 912, 1992, 2828, 38]
for number in numbers:
    print("{:6d}".format(number))

This gives me:

192829
 88288
   912
  1992
  2828
    38

This works, because I knew that longest number is 6 digits long, so I hardcoded 6: "{:6d}"

What if I don't know the longest number. The only solution I can think of, is the following.

length = len(str(max(numbers)))
output_template = "{:" + str(length) + "d}"
for number in numbers:
    print(output_template.format(number))

Is there a better way?

Upvotes: 0

Views: 141

Answers (4)

GLHF
GLHF

Reputation: 4044

Here is another way;

numbers = [192829, 88288, 912, 1992, 2828, 38,4536,3564576,2342342]
maxlen=len(max(str(numbers),key=len))
print (("{:^{dif}}\n"*len(numbers)).format(*numbers,dif=maxlen))

Upvotes: 0

Hackaholic
Hackaholic

Reputation: 19763

this you can try:

>>> numbers = [192829, 88288, 912, 1992, 2828, 38]
>>> length = len(str(max(numbers)))    # max give you larget number and len find its length
>>> for x in numbers:
...     print("{:{}d}".format(x,length))
... 
192829
 88288
   912
  1992
  2828
    38

Upvotes: 0

palsch
palsch

Reputation: 7066

len(str(max(numbers))

gives you the length of the biggest number, so you can use this

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180512

You can pass a variable into str.format, you don't need to create a template:

numbers = [192829, 88288, 912, 1992, 2828, 38]
for number in numbers:
    print("{0:{1}d}".format(number,len(str(max(numbers)))))

Upvotes: 3

Related Questions