0

I'm working in a command line tool that prints keys and values from a dict, and wondering what is the proper way to solve two indentation problems I have:

1st problem:

should be:

short key       value
very long key   value

when using /t between the key and the value I get:

short key   value
very long key   value

2nd problem

should be:

key    longggggggggg
       gggg value

but I get:

key    longggggggggg
gggg value

Thanks for the help! :)

Moran
  • 11
  • 1
  • 1
    It's up to the client/terminal how it displays hard tab characters. If you need more control you might just want to manage [leading] spaces yourself and not use tabs at all. – Tom Dalton May 12 '20 at 14:40
  • See [this post](https://stackoverflow.com/questions/10837017/how-do-i-make-a-fixed-size-formatted-string-in-python) – Simon Martineau May 12 '20 at 14:44
  • @SimonMartineau thanks for the link, it indeed helped me with the 1st problem. 2nd problem still up for takers :) – Moran May 12 '20 at 18:03

1 Answers1

0

Say you have the following dict:

items = {'first_key': 'normal_length', 'second_key': 'veeeeeeeeeeeeryyyyyyyyy_loooooong_value'}

You could do something like this

n = 20  # Max horizontal length for the value
for key, value in items:
    print('{:<20}     {:<n}'.format(key, value))
    if len(str(value)) > 20:
        for sub_string in [str(value)[i:i+n] for i in range(n, len(str(value), n))]:
            print(' '*25 + sub_string)

You start by doing what you do normally, then you iterate over each substring of length 20 after the first one. I did not test this but it is just a path for you

Simon Martineau
  • 210
  • 2
  • 8