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

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


future-fstrings brings f-strings to Python 2.7 scripts. (And I assume 3.3-3.5 based on the documentation.)

Once you pip install it via pip install future-fstrings, you have to place a special line at the top of your code. That line is:

# -*- coding: future_fstrings -*-

Then you can use formatted string literals (f-strings) within your code:

# -*- coding: future_fstrings -*-var = 'f-string'print(f'hello world, this is an {var}')


Unfortunatly if you want to use it you must require Python 3.6+, same with the matrix multiplication operator @ and Python 3.5+ or yield from (Python 3.4+ I think)

These made changes to how the code is interpreted and thus throw SyntaxErrors when imported in older versions. That means you need to put them somewhere where these aren't imported in older Pythons or guarded by an eval or exec (I wouldn't recommend the latter two!).

So yes, you are right, if you want to support multiple python versions you can't use them easily.


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.