I honestly implemented what you are saying. Here is my code.
import re
def myFormat(string):
for i in re.finditer(r"%([(][^)]*[)])", string):
string = re.sub(re.escape(i.group(0)), " "*eval(i.group(1)), string)
return string
dev, size, calc, stat = "Device", "Size", "Calculated", "Status"
x1, x2, x3 = 3, 6, 10
print myFormat("%s%(15-x1)%s%(15-x2)%s%(15-x3)%s")%(dev, size, calc, stat)
output:
'Device Size Calculated Status'
UPDATE:
Why "TypeError: format requires a mapping" occur?
Python allows to write expression as below.
print "%(something)d"%{"something":123}
print "%(something)s"%{"something":"abc"}
So the part of your code, ie:
"%s%(15-x1)..."%(dev,...)
-------- --------
| ^
| |
+-------------+
Python interpreter expect {'15-x1':xxx, ...} here.
This is the cause of the error.
So following code raises no error. But it's output is nonsense.
"%s%(15-x1)%s%(15-x2)%s%(15-x3)%s"%{'15-x1':"abc", '15-x2':"def", '15-x3':"ghi"}
If you use %(something)
in string and want to format it by using %
, you need to use dict
. Otherwise error TypeError: format requires a mapping
occur.