So lets say I have a function where I print a numbered list, all is good until the index becomes double digits. if the list is long enough, it wont be formatted as neatly as it could. So the obvious thing to do would be seperate the data from the number with a tab. But just for simplicities sake, is it possible to fill the blank space taken up with the tab space with dots (as is sometimes seen in lists with large distances between the value and number)
Heres what I got.
print('\n--Shopping List--')
with open("ShoppingList.txt","r") as lst:
for index, data in enumerate(lst, start=1):
print("{}. {}".format(index, data),end='')
print()
The output of this is:
--Shopping List--
1. item1
2. item2
3. item3
4. item4
5. item5
6. item6
7. item7
8. item8
9. item9
10. item10
11. item11
12. item12
13. item13
14. item14
15. item15
as you can see the items get pushed out at the double digits.
The desired output would look like this
--Shopping List--
1....item1
2....item2
3....item3
4....item4
5....item5
6....item6
7....item7
8....item8
9....item9
10...item10
11...item11
12...item12
13...item13
14...item14
15...item15
In short: I want something that works like \t but instead of giving me whitespace, gives me dots. Is there a simple way to do this that doesnt involve a bunch of math calculating the amount of dots I need?
>Solution :
str.ljust(n, char) to the rescue:
>>> for n, text in enumerate(["foo", "bar", "baz"]):
... print(f"{str(n).ljust(4, '.')}{text}")
...
0...foo
1...bar
2...baz
Alternately, using modern format strings,
>>> for n, text in enumerate(["foo", "bar", "baz"]):
... print(f"{n:.<4}{text}")
...
0...foo
1...bar
2...baz