f.strings
In Python you can format string in a variety of ways.We learned how to use a %format technique in last post. In Python version 3.7 introduced f.string .
f/F strings are literals begins with letter f/F and It uses { }, curly braces for replacement of expressions with their values
spyder_version=3 python_version=2.7 print(f'I am using Spyder ID {spyder_version} with Python {python_version}') #Output I am using Spyder ID 3 with Python 2.7
Arbitrary expression
F"{10*10}" #Output 100
Function call
We can also call function inside f.strings.
def multi(x,n): return x*n f'{multi(2,2)}'
Multipleline
f-strings are faster than % formatting because they ares constants while f.string expressions are evaluated at runtime.
Also it is possible compose f.strings in multiple line. All strings must begin with ‘f/F’.
>>>>version =3.8 >>say=(f'I want to use {topic}' f' in {lang}' f' version {version}') >>say Out[20]: 'I want to use panda frames in python version 3.8'
It can also be rewritten using ‘\’
>>say=f'I want to use {topic}' \ f' in {lang}' \ f' version {version}'
One thought on “Python Library Tips: f.strings”