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

前端 未结 8 1331
臣服心动
臣服心动 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:19

    I've been using 'str'.format(**locals()) for a while but made this after a while because the additional code was a bit cumbersome for each statement

    def f(string):
        """
        Poor man's f-string for older python versions
        """
        import inspect
    
        frame = inspect.currentframe().f_back
    
        v = dict(**frame.f_globals)
        v.update(**frame.f_locals)
    
        return string.format(string, **v)
    
    # Example
    GLOBAL = 123
    
    
    def main():
        foo = 'foo'
        bar = 'bar'
    
        print(f('{foo} != {bar} - global is {GLOBAL}'))
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题