f-strings have made life easier for Python developers. They are of the form f" {} " where the curly brackets are optional. The advantage of curly brackets is that expressions can be evaluated within f-strings at runtime and printed to the screen. We need not cast the variable to string format anymore. They have been around since Python 3.6
How to restrict decimal to n positions for a float variable?
pi= 22/7
f"Value of pi upto 2 decimal positions is {pi:0.2f}"
--->Value of pi upto 2 decimal positions is 3.14
f"Value of pi upto 3 decimal positions is {pi:0.3f}"
--->Value of pi upto 3 decimal positions is 3.143
f"Value of pi upto 4 decimal positions is {pi:0.4f}"
--->Value of pi upto 4 decimal positions is 3.1429
f"Value of pi with no decimal position is {pi:0.0f}"
--->Value of pi with no decimal position is 3
How to format a fraction as a Percentage using f-strings?
perc = 0.55555344
f"Harry has secured {perc:%} in Physics"
--->Harry has secured 55.555344% in Physics
###Format perecentage to 2 decimals####
f"Harry has secured {perc:.2%} in Physics"
---> Harry has secured 55.56% in Physics
How to format a large number using commas for better readability using f-strings?
Networth = 3444444444445
f"${Networth:,} is your Networth"
--->$3,444,444,444,445 is your Networth
Comments
Post a Comment