Open Winand opened 6 years ago
Thanks!
This code doesn't format text, it just puts field contents into square brackets and parses }}
as expected. Just an idea of algorithm.
def formats(pt, *args, **kw):
ret = ""
p = 0
ln = len(pt)
while True:
op = pt.find("{", p)
cl = pt.find("}", p)
if op > -1 and (op < cl or cl == -1): # {
if op == ln - 1: # opening { is the last char
raise ValueError("Single '{' encountered in format string")
elif pt[op+1] == "{": # double {
ret += pt[p: op+1]
p = op + 2 # {{
elif cl > -1: # a field
ret += pt[p: op]
ret += "[" + pt[op+1: cl] + "]" # FIELD
p = cl + 1
else: # no closing }
raise ValueError("Single '{' encountered in format string")
elif cl > -1:
if pt[cl+1] == "}":
ret += pt[p: cl+1]
p = cl + 2 # }}
else:
raise ValueError("Single '}' encountered in format string")
else:
ret += pt[p:]
break
return ret
Suddenly i've found out that there's a special case: '{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)
In Python you can put field inside format part (after :
) of another field. Only 1 level of nesting is supported. But it makes things more complicated.
pscript gives right result if I use two opening brackets and one closing bracket (3rd line) Python gives the same result with two opening and two closing brackets (2nd line)