-1

I have a long list of rankings, like so:

1. xxx
2. xxx
...
14. xxx
...
456. xxx

As you can see, the width is different for each line. I meddled with zfill(), but I don't know how to insert the correct amount of zeroes depending on the length of the widest entry.

Any help would be appreciated.

Edit: my rankings list is a list like ['player 1', 'player 7', 'player 8']

  • 1
    Possible duplicate of [String.format() to fill a string?](https://stackoverflow.com/questions/3450758/string-format-to-fill-a-string) – Netwave Apr 22 '19 at 08:16
  • @Netwave that's a java question while this is python. They're closely related, but does it make them a duplicate? – Ignatius Apr 22 '19 at 09:45
  • @Taegyung, good point indeed. Just trusted the filter. Let me update – Netwave Apr 22 '19 at 09:46

2 Answers2

0

You can evaluate the length in digits of the longest entry by evaluating the length of its length. For example, 99 is 2 digits long, and len(str(99)) is 2, meaning two characters are needed. We can then take advantage of f-string formatting to produce the following result:

for x in range(len(rankings)):
    print(f'{x+1:0{len(str(len(rankings)))}}. xxx')

Example:

rankings = [1]*5

for x in range(len(rankings)):
    print(f'{x+1:0{len(str(len(rankings)))}}. xxx')

produces this result:

1. xxx
2. xxx
3. xxx
4. xxx
5. xxx
>>>

while

rankings = [1]*50

for x in range(len(rankings)):
    print(f'{x+1:0{len(str(len(rankings)))}}. xxx')

produces this result:

01. xxx
02. xxx
03. xxx
04. xxx
05. xxx
06. xxx
07. xxx
08. xxx
09. xxx
10. xxx
11. xxx
12. xxx
13. xxx
14. xxx
15. xxx
16. xxx
17. xxx
18. xxx
19. xxx
20. xxx
21. xxx
22. xxx
23. xxx
24. xxx
25. xxx
26. xxx
27. xxx
28. xxx
29. xxx
30. xxx
31. xxx
32. xxx
33. xxx
34. xxx
35. xxx
36. xxx
37. xxx
38. xxx
39. xxx
40. xxx
41. xxx
42. xxx
43. xxx
44. xxx
45. xxx
46. xxx
47. xxx
48. xxx
49. xxx
50. xxx
>>> 
Alec
  • 8,529
  • 8
  • 37
  • 63
0

This is one approach using max with len

Ex:

data = ["1. xxx", "2. xxx", "14. xxx", "456. xxx"]
fill_value = len(max(data, key=lambda x: len(x)))
for i in data:
    print(i.zfill(fill_value))

Output:

001. xxx
002. xxx
014. xxx
456. xxx
Rakesh
  • 81,458
  • 17
  • 76
  • 113