Can I import Python's 3.6's formatted string literals (f-strings) into older 3.x, 2.x Python?

前端 未结 8 1339
臣服心动
臣服心动 2020-12-15 02:27

The new Python 3.6 f-strings seem like a huge jump in string usability to me, and I would love to jump in and adopt them whole heartedly on new projects which might be runni

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 03:13

    A dirty solution using simpleeval

    import re
    import simpleeval
    test='_someString'
    lst = ['_456']
    
    s = '123123{lst[0]}{test}'
    
    def template__format(template, context=None):
        if context is None:
            frame = inspect.currentframe()
            context = frame.f_back.f_locals        
            del frame
        ptn =  '([^{]?){([^}]+)}'
        class counter():
            i = -1
    
        def count(m):
            counter.i += 1
            return m.expand('\\1{%d}'%counter.i)
    
        template = re.sub(ptn,string=s, repl= count)
        exprs = [x[1] for x in re.findall(ptn,s)]
        vals = map(simpleeval.SimpleEval(names=context).eval,exprs)
        res = template.format(*vals)
        return res
    
    print (template__format(s))
    
    

提交回复
热议问题