简体   繁体   中英

How can I use the value of a variable in Python format string

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'

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() .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM