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

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

    here's what I use:

    text = "Foo is {age} {units} old".format(**locals())
    

    it unpacks (**) the dict returned by locals() which has all your local variables as a dict {variable_name: value}

    Note this will not work for variables declared in an outer scope, unless you import it to the local scope with nonlocal (Python 3.0+).

    you can also use

    text.format(**locals(),**globals())
    

    to include global variables in your string.

提交回复
热议问题