0

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?

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.