flexxui / pscript

Python to JavaScript compiler
http://pscript.readthedocs.io
BSD 2-Clause "Simplified" License
260 stars 25 forks source link

curly brackets in string format #20

Open Winand opened 6 years ago

Winand commented 6 years ago

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)

_pymeth_format.call('{"search":"{0}","source_lang": "{1}", "target_lang":"{2}"}', "phrase1", "lang1", "lang2");
"undefined","source_lang": "lang1", "target_lang":"lang2"}"

_pymeth_format.call('{{"search":"{0}","source_lang": "{1}", "target_lang":"{2}"}}', "phrase1", "lang1", "lang2");
"{"search":"phrase1","source_lang": "lang1", "target_lang":"lang2"}}"

_pymeth_format.call('{{"search":"{0}","source_lang": "{1}", "target_lang":"{2}"}', "phrase1", "lang1", "lang2");
"{"search":"phrase1","source_lang": "lang1", "target_lang":"lang2"}"
almarklein commented 6 years ago

Thanks!

Winand commented 6 years ago

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.