Skip to main content

Command Palette

Search for a command to run...

Learn Python #4 - The f-string...

Published
2 min read
Learn Python #4 - The f-string...
N

Seasoned JavaScript Developer who loves to explore other programming languages like Python. A problem solver, tech lover by heart. Loves reading booking, and cooking. 🤩🚀🔬

Hello everyone today we are going to talk about string manipulation via f-string.

Python over the years has provided many features and one of them is to format the string.

What the f-strings is 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 string Steve 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

  • 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

O

I prefer to use the f string to the format or C-style formatting

More from this blog

N

nitinreddy3

43 posts

Seasoned JavaScript Developer who loves to explore other programming languages like Python. A problem solver, tech lover by heart. Loves reading booking, and cooking. 🤩🚀🔬