2

Please tell me something like this is possible in Python. I can't seem to get it to work

MY_LENGTH_CONSTRAINT = 24
myFormatStr = '{mykey:<${MY_LENGTH_CONSTRAINT}s}'
myStr = myFormatStr.format(mykey='Something')

I keep getting

KeyError: 'MY_LENGTH_CONSTRAINT'

1 Answer 1

4

Add mcl = MY_LENGTH_CONSTRAINT to the parameters fed to format:

MY_LENGTH_CONSTRAINT = 24
myFormatStr = '{mykey:<{mlc}s}'
myStr = myFormatStr.format(mykey='Something',
                           mlc = MY_LENGTH_CONSTRAINT)
print(myStr)
# Something               

You can also refer to local variables in your format string, and inform format of the values by passing it **locals():

MY_LENGTH_CONSTRAINT = 24
myFormatStr = '{mykey:<{MY_LENGTH_CONSTRAINT}s}'
myStr = myFormatStr.format(mykey='Something', **locals())
print(myStr)
# Something               

(or similarly, use global variables, and pass format **globals().)

Sign up to request clarification or add additional context in comments.

1 Comment

Of course, but I was wondering if this could be done implicitly. I believe ruby has a feature like the one I'm looking for here in Python.

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.