0

I want to print the content of a Python config parser object.

The following code

for section in system_config.config.sections():
    print ("\n[" + section + "]")
    for (key, value) in system_config.config.items(section):
          print(key + "=" + value)

prints

[GENERAL]
data_roots=[["c:\\data", "/data"] , ["d:\\data2", "/data2"]] 
test_data_folder=c:\data\atp-test-data
mount_render_python_apps=false
mount_render_modules=false
host_memory=24
host_number_of_cores=4
at_core_threads=15

For readability, the following is preferable:

[GENERAL]
data_roots                = [["c:\\data", "/data"] , ["d:\\data2", "/data2"]] 
test_data_folder          = c:\data\atp-test-data
mount_render_python_apps  = false
mount_render_modules      = false
host_memory               = 24
host_number_of_cores      = 4
at_core_threads           = 15

In C++ this can be achieved by setting the 'width' of the first field when using the stream operator '<<'.

Question is, how to do this with Python?

Totte Karlsson
  • 1,261
  • 1
  • 20
  • 55

3 Answers3

5

You can use {:<30} format to align strings up to 30 of length to left here is a full example:

import random
import string

def randomstr():
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(random.randint(1,30)))


for _ in range(10):
    print('{:<30} = {}'.format(randomstr(), randomstr()))

Sample output

ohpy                           = bxqoknodteueocokveygkdxmzzxubi
rsulmvnqeyeihchanxrggorlm      = vtfeu
cvuhpavispkfbttbadt            = d
dgfcqtswqjvywosiikkjdmpyvjhoo  = ijx
ainrzifrjrkqfanrxyczs          = aluoaoizxtmcrvqv
zpujlyopvrucjqugtaamu          = pezh
eot                            = uizfrxpkjywtlxbgzhrcuuj
hfavmswauekyrtgzrhyxwmbgcyzfq  = znwfpuosysirtbkiiimzjkifbueq
qxsqzwkyafcwjrjwnwlradrudush   = barehtexzpku
hntgerexophiqbafmwfwdomas      = frtsmtakcfztlwfesiijacbmocksqq

You may not know the maximum length of your key strings. But you can do it with something like this in your case maxlen = max(len(k) for k in system_config.config.keys()) and using maxlen in format like this '{:<{width}} = {}'.format(randomstr(), randomstr(), width=maxlen)

geckos
  • 5,687
  • 1
  • 41
  • 53
  • 2
    For reference to OP, [here's the documentation on string formatting](https://docs.python.org/3/library/string.html#string-formatting) – Green Cloak Guy Jun 12 '19 at 17:44
0

.format method of a string, or an f-string.

print( '{:<20}={}'.format(key,value) ) # python 2 friendly
#or
print( f'{key:<20}={value}' )

20 is a guess at the width, I haven't counted it.

nigel222
  • 7,582
  • 1
  • 14
  • 22
0

Python's built-in str class has an ljust method which performs left text justification given a width and an optional character to fill with.

for section in system_config.config.sections():
    print ("\n[" + section + "]")
    max_len = max(len(key) for key, _ in system_config.config.items(section))
    for key, value in system_config.config.items(section):
          print(f'{key.ljust(max_len)} = {value}')
TrebledJ
  • 8,713
  • 7
  • 26
  • 48