Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 running on older interpreters. 2.7, 3.3-3.5 support would be great but at the very least I would like to use these in Python 3.5 code bases. How can I import 3.6's formatted string literals for use by older interpreters?

I understand that formatted string literals like f"Foo is {age} {units} old" are not breaking changes, so would not be included in a from __future__ import ... call. But the change is not back-ported (AFAIK) I would need to be sure that whatever new code I write with f-strings is only ran on Python 3.6+ which is a deal breaker for a lot of projects.

like image 436
zachd1_618 Avatar asked Feb 07 '17 18:02

zachd1_618


People also ask

Does Python 3.6 support F strings?

As of Python 3.6, f-strings are a great new way to format strings. Not only are they more readable, more concise, and less prone to error than other ways of formatting, but they are also faster!

How do I import an F-string into Python?

To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str. format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.

Does Python 2.7 support F strings?

Because Python 2.7 will never support f-strings, there is nothing to be gained by being able to combine the 'f' prefix with 'u'.

Which string format is currently recommended to be used in Python?

Python uses C-style string formatting to create new, formatted strings.


1 Answers

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}') 
like image 140
Wayne Avatar answered Oct 09 '22 21:10

Wayne