Search code examples
pythonstring-formatting

Adding additional characters into the String Formatting key field


I am trying to create a basic key/value table that looks like below:

someKey:               some info
aReallyLongKey:        more info
somthingElse:          other info

Without the colons, this is really easy:

formatter = "{key:<25}{value}"

for k,v in myDict.items():
    print(formatter.format(key=k, value=v))

However, this will not include the ":" after the key. What I want is something like this (this doesn't work):

formatter = "{key+':':<25}{value}"

Essentially, I want to append something to the key so that I get: formatter.format(key=k+":", value=v), but with the appended ":" in the formatter string.

I've tried doing some nesting, but couldn't get that to work. Is there an elegant, native, Pythonic way to append the ":" to the key in the string formatter so that I can still use the <25 formatting over the entire "key:" part?


Solution

  • If you're using python 3.6+ you can do this easily using f-strings:

    for k,v in myDict.items():
        print(f"{f'{k}:':<25}{v}")
        #or
        print(f"{k + ':':<25}{v}")
    

    Otherwise just append the colon before it's formatted (just like you were asking):

    formatter = "{key:<25}{value}".format
    for k,v in myDict.items():
        print(formatter(key=k+':', value=v))