Hello everyone today we are going to talk about string manipulation via f-string
.
Python over the years has provided many features, one of which is to format the string.
What f-strings
is it all about?
f-strings is a literal string interpolation (The way it works in JavaScript -> string literals).
It provides a convenient way to embed the python expressions with ease.
Let us look at the examples:-
- If I want to format a string wherein some of the values are received from a variable
employee_name = 'Steve Rogers'
and we have to generate a stringSteve Rogers is one of the greatest Marvel superheroes
then we need to do ->
f"{employee_name} is one of the greatest Marvel superheroes"
// Steve Rogers is one of the greatest Marvel superheroes
- You can also inject numeric values inside the string
quantity_bat = 10
price_bat = 10
f"The total cost of {price_bat} bats is ${quantity_bat*price_bat}"
//The total cost of {price_bat} bats is 100
- If you want to show the values with a 2 decimal point limit
quantity_bat = 10.99
price_bat = 10.234
f"The total cost of {price_bat} bats is ${quantity_bat*price_bat:,.2f}"
//output -> 'The total cost of 10.234 bats is $112.47'
In the above example we can decide up to which decimal points we want to show the number
- If you want to use double quotes, yes you can do that as well
number_one = 1
f"\"{number_one}\" is a odd number"
// 1 is a odd number
Conclusion
f-strings are easy to understand, use and handy when it comes to string interpolation, so do let me know what you guys think of this article💡.
Thanks in advance for reading this article…🚀
More than happy to connect with you on
You can also find me on