请告诉我这样的事情在Python中是可行的。我似乎无法让它工作
MY_LENGTH_CONSTRAINT = 24
myFormatStr = '{mykey:<${MY_LENGTH_CONSTRAINT}s}'
myStr = myFormatStr.format(mykey='Something')
我一直在
KeyError: 'MY_LENGTH_CONSTRAINT'
答案 0 :(得分:4)
将mcl = MY_LENGTH_CONSTRAINT
添加到输入format
的参数:
MY_LENGTH_CONSTRAINT = 24
myFormatStr = '{mykey:<{mlc}s}'
myStr = myFormatStr.format(mykey='Something',
mlc = MY_LENGTH_CONSTRAINT)
print(myStr)
# Something
您还可以在格式字符串中引用局部变量,并通过传递format
来告知值**locals()
:
MY_LENGTH_CONSTRAINT = 24
myFormatStr = '{mykey:<{MY_LENGTH_CONSTRAINT}s}'
myStr = myFormatStr.format(mykey='Something', **locals())
print(myStr)
# Something
(或类似地,使用全局变量,并传递format
**globals()
。)