To create an f-string, add a string with the letter "f". The string itself can be formatted in much the same way as Output: Code # 2: # Python3 program representing the f-string
val
=
’Geeks’
print
(f
"{val} for {val} is a portal for {val}."
)
name
=
’Tushar’
age
=
23
print
(f
"Hello, My name is {name} and I’m {age} years old. "
)
Hello, My name is Tushar and I’m 23 years old. Python.Engineering is a portal for Geeks.
|
Output:
April 04, 2018
Note: F-strings are faster than the two most commonly used string formatting mechanisms: % formatting
and str .format ()
.
Y Let’s take a look at a few examples of errors that can occur when using an f-line:
Code # 3: Demonstrate a syntax error.
| tr>
Code # 4: The backslash cannot be used directly in a format string.
|
Output:
Traceback (most recent call last): Python Shell, prompt 29, line 1 Syntax Error: f-string exp ression part cannot include a backslash:, line 1, pos 0
But the documentation indicates that we can put a backslash in a variable as a workaround:
|
Output:
newline: 10
Link: PEP 498, Literal String Interpolation