What's New In Python 3.6
[CG]Maxime
22.1K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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}"
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content