String with 'f' prefix in python-3.6

2020-01-24 04:29发布

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?

5条回答
时光不老,我们不散
2楼-- · 2020-01-24 04:42

letter f for "format" as in f"hello {somevar}. This little f before the "(double-quote) and the {} characters tell python 3, "hey, this string needs to be formatted. So put these variable in there and format it.".

hope this is clear.

查看更多
你好瞎i
3楼-- · 2020-01-24 04:42

i had issue like this, in the line of imported module: response_json = requests.get(f'{self.api_url}/{path}', params).json() i fixed it like this:

response_json = requests.get('{}/{}'.format(self.api_url, path), params).json()
查看更多
贼婆χ
4楼-- · 2020-01-24 04:44

It might also be worth noting that this PEP498 has a backport to Python <3.6

pip install fstring

from fstring import fstring

x = 1

y = 2.0

plus_result = "3.0"

print fstring("{x}+{y}={plus_result}")

# Prints: 1+2.0=3.0
查看更多
Fickle 薄情
5楼-- · 2020-01-24 04:53

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.

查看更多
beautiful°
6楼-- · 2020-01-24 04:58

f-strings also support any Python expressions inside the curly braces.

print(f"My cool string is called {name.upper()}.")
查看更多
登录 后发表回答