I need to align numbers right for any input. However I can't seem to do it only for a specific input not for any input. I've also tried turning the list of strings into a list of nums using list comprehension
and then do print("{:5d}".format(i))
. I've also tried doing something like print("{:>len(i)}".format(i))
n = input().split()
m = sorted(n, key =int, reverse = True)
for i in m:
print("{:>10}".format(i))
Sample Input:
8 11 12 123 45678
Sample Output:
45678
123
12
11
8
I've managed to do it for the input above, but not for any input.
CodePudding user response:
maybe it could generalize better by keeping your elements as strings and using rjust() ?
n = input().split()
for i in n:
print(i.rjust(len(max(n, key = len))))
CodePudding user response:
You can use a variable width specifier in string formatting:
n = input().split()
l = max(len(i) for i in n)
m = sorted(n, key=int, reverse=True)
for i in m:
print("{:>{:d}}".format(i, l))
With an input of 1231231232131213 123123213213 12312321321 213123123
, the output is:
1231231232131213
123123213213
12312321321
213123123