Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to use dots as tabspaces?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

--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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading