0

I am making a UI for termux terminal on android.

This code below prints the content of the directory.

It works perfectly fine but the output is not even, ie, irregular spaces between the columns.

I've seen people using format but in my case the end argument value differ on each print.

output

def display_dir(dir_name):
    direc = os.listdir(dir_name)
    for index, d in enumerate(direc):
    if index % 2 == 0:
        print(f"{index}- {d}", end=" " * 10)
    else:
        print(f"{index}- {d}", end="\n")

but I want perfectly aligned 2 column output.I've tried many things. Is there a short way to do this?

I actually have a solution where I check the longest string and add white spaces for remaining strings but it's not optimal.

nTheta
  • 539
  • 3
  • 12
  • Does this answer your question? [How to print a list more nicely?](https://stackoverflow.com/questions/1524126/how-to-print-a-list-more-nicely) – Tomerikoo Feb 15 '21 at 17:27
  • Does this answer your question? [Create nice column output in python](https://stackoverflow.com/questions/9989334/create-nice-column-output-in-python) – AnsFourtyTwo Feb 15 '21 at 17:27
  • @Tomerikoo it deleted some elements from the list and I need indexing too which I couldn't find. – nTheta Feb 15 '21 at 17:39
  • @AnsFourtyTwo the post you suggested is for nested lists. Mine is a single list. But I might try slicing it....thanks btw. – nTheta Feb 15 '21 at 17:41
  • Sure, it's just to get the idea. – AnsFourtyTwo Feb 15 '21 at 18:18

1 Answers1

0

You are probably looking for something like this:

def display_dir(dir_name):
    direc = os.listdir(dir_name)
    max_len = len(max(direc, key=len))

    for index, d in enumerate(direc):
        if index % 2 == 0:
            print("{:2}- {:<{}}".format(index, d, max_len), end=" ")
        else:
            print("{:2}- {:<{}}".format(index, d, max_len), end="\n")

Or even further:

def display_dir(dir_name):
    direc = os.listdir(dir_name)
    
    max_len_even = len(max(direc[::2], key=len))
    max_len_odd = len(max(direc[1::2], key=len))
    index_pad_len = len(str(len(direc)))

    for index, d in enumerate(direc):
        if index % 2 == 0:
            print("{:{}}- {:<{}}".format(index, index_pad_len, d, max_len_even), end=" ")
        else:
            print("{:{}}- {:<{}}".format(index, index_pad_len, d, max_len_odd), end="\n")
Nerveless_child
  • 1,366
  • 2
  • 15
  • 19