F-string in Python

 ' f-string ' Formatting

Python f-strings are a simple and efficient way to format strings. The f-strings make it easy to embed variables directly into a string.

Introduced in Python version 3.6 in late 2016, f-strings significantly changed the conventional method of using separate formats for different data types such as floats, integers, and strings. 

Here's the basics:

How to Use:

  • Start your string with an f or F before the quotation marks.
  • Inside the string, put any variables or expressions you want to use inside curly braces {}.

  • name = "Romanch"
    age = 25
    print(f"My name is {name} and I am {age} years old.")

    Output: My name is Romanch and I am 25 years old.

    Why f-strings?

    • Readable: It’s easy to see what the final string will look like, and the code is concise.

    • Efficient: f-strings are faster than other formatting methods; like format() or %.

    • Flexible: You can include expressions and calculations inside {}, not just variables.

    x = 5
    y = 10
    print(f"The sum of {x} and {y} is {x + y}.")

    Output: The sum of 5 and 10 is 15.

    Formatting with f-strings:

    • You can format numbers, dates, and more with f-strings.
    price = 49.9876
    print(f"The price is ${price:.2f}")

    Output: The price is $49.99


    In short, f-strings make it easy to create formatted strings by directly embedding variables or expressions in a readable and efficient way!

    Comments

    Popular posts from this blog

    Deploy Quasar + Laravel + MySQL on AWS EC2 (Default VPC)

    Nginx Load Balancing Lab on AWS EC2

    EC2 Fundamentals