[924] f-strings in Python

发布时间 2023-10-23 12:42:56作者: McDelfino

ref: f-strings in Python

ref: Python's F-String for String Interpolation and Formatting


F-strings, also known as formatted string literals, are a feature introduced in Python 3.6 that provide a concise and convenient way to embed expressions inside string literals. F-strings are often used for string interpolation, making it easy to insert variables and expressions into strings. They are created by prefixing a string with the letter 'f' or 'F' and enclosing expressions in curly braces {}.

Here's a basic example of how to use f-strings in Python:

name = "Alice"
age = 30

# Create an f-string
greeting = f"Hello, my name is {name} and I am {age} years old."

print(greeting)

In this example, the f-string greeting contains placeholders {name} and {age}. When the f-string is evaluated and printed, these placeholders are replaced with the values of the corresponding variables, resulting in the final string "Hello, my name is Alice and I am 30 years old."

F-strings offer several advantages:

  1. Readability: F-strings make the code more readable and concise, as you can embed variables directly within the string, making it clear what's being inserted.

  2. Expressions: You can include expressions, not just variables, within the curly braces. This allows you to perform calculations or format values directly within the string.

    num1 = 10
    num2 = 20
    result = f"The sum of {num1} and {num2} is {num1 + num2}."
  3. Formatting: F-strings support various formatting options for numbers, dates, and other data types. For example, you can format floating-point numbers to a specific decimal place or dates in a particular format.

    price = 49.99
    formatted_price = f"The price is ${price:.2f}"
  4. Multiline Strings: F-strings can also be used for multiline strings, making it easy to create formatted text with line breaks and indentation.

    message = f"""Dear {name},
    
    Thank you for your order.
    
    Sincerely,
    Your Company"""

Keep in mind that f-strings are available in Python 3.6 and later versions. They are a powerful tool for string formatting and are widely used in modern Python code for their readability and flexibility.