What's New In Python 3.6
[CG]Maxime
21.5K views
PEP 498: Formatted string literals
PEP 498 introduces a new kind of string literals: f-strings, or formatted string literals.
Formatted string literals are prefixed with 'f'
and are similar to the format strings accepted by str.format(). They contain replacement fields surrounded by curly braces. The replacement fields are expressions, which are evaluated at run time, and then formatted using the format() protocol:
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
'result: 12.35'
** See also: **
PEP 498 – Literal String Interpolation.
PEP written and implemented by Eric V. Smith.
Example
Fix the following source code to make it work.
Literal String Example
1
2
3
4
5
6
def compute_sum(a, b, precision):
""" Returns a string showing the sum of a and b as in the following example:
Let a = 3.1, b = 2.2 and precision=4, the expected result is "3.1 + 2.2 = 5.3"
"""
return f"{a} + {b} = {a + b}"
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.