Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String with 'f' prefix in python-3.6

I'm trying out Python 3.6. Going through new code, I stumbled upon this new syntax:

f"My formatting string!" 

It seems we can do things like this:

>>> name = "George" >>> print(f"My cool string is called {name}.") My cool string is called George. 

Can anyone shed some light on the inner workings of this? In particular what is the scope of the variables that an f-prefixed string can take?

like image 735
DevShark Avatar asked Mar 02 '16 10:03

DevShark


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!

Does Python 3.5 support F strings?

f-strings not supported in Python 3.5 or below #250.

What is F prefix in Python?

In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values. Some examples are: >>> import datetime >>> name = 'Fred' >>> age = 50 >>> anniversary = datetime.

How do you type an F-string in Python?

What are f-Strings in Python? Strings in Python are usually enclosed within double quotes ( "" ) or single quotes ( '' ). To create f-strings, you only need to add an f or an F before the opening quotes of your string. For example, "This" is a string whereas f"This" is an f-String.


1 Answers

See PEP 498 Literal String Interpolation:

The expressions that are extracted from the string are evaluated in the context where the f-string appeared. This means the expression has full access to local and global variables. Any valid Python expression can be used, including function and method calls.

So the expressions are evaluated as if they appear in the same scope; locals, closures, and globals all work the same as in other code in the same context.

You'll find more details in the reference documentation:

Expressions in formatted string literals are treated like regular Python expressions surrounded by parentheses, with a few exceptions. An empty expression is not allowed, and a lambda expression must be surrounded by explicit parentheses. Replacement expressions can contain line breaks (e.g. in triple-quoted strings), but they cannot contain comments. Each expression is evaluated in the context where the formatted string literal appears, in order from left to right.

Since you are trying out a 3.6 alpha build, please do read the What's New In Python 3.6 documentation. It summarises all changes, including links to the relevant documentation and PEPs.

And just to be clear: 3.6 isn't released yet; the first alpha is not expected to be released until May 2016. See the 3.6 release schedule.

like image 65
Martijn Pieters Avatar answered Oct 06 '22 09:10

Martijn Pieters