Popular Searches

What is f-string?

0368

An f-string, or formatted string literal, is a feature in Python that allows you to embed expressions inside string literals, using curly braces {}. This makes it easy to create strings that include variable values or expressions directly within the string.

Key Features of f-strings:

  1. Syntax:

    • An f-string is created by prefixing a string with the letter f or F.
    • Example:
      name = "Alice"
      greeting = f"Hello, {name}!"  # Outputs: "Hello, Alice!"
      
  2. Expression Evaluation:

    • You can include any valid Python expression inside the curly braces, and it will be evaluated at runtime.
    • Example:
      age = 30
      message = f"{name} is {age} years old."  # Outputs: "Alice is 30 years old."
      
  3. Formatting Options:

    • You can format numbers, dates, and other types directly within the f-string.
    • Example:
      height = 1.75
      formatted_string = f"Height: {height:.2f} meters"  # Outputs: "Height: 1.75 meters"
      
  4. Multi-line f-strings:

    • f-strings can also span multiple lines using triple quotes.
    • Example:
      info = f"""
      Name: {name}
      Age: {age}
      """
      

Advantages of f-strings:

  • Readability: They make the code easier to read and understand compared to older formatting methods (like % formatting or str.format()).
  • Performance: f-strings are generally faster than other string formatting methods because they are evaluated at runtime.

Example:

Here’s a complete example demonstrating the use of f-strings:

name = "John"
age = 25
height = 1.82

output = f"{name} is {age} years old and {height:.2f} meters tall."
print(output)  # Outputs: "John is 25 years old and 1.82 meters tall."

If you have any further questions about f-strings or need more examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!