Formatted String

Python Formatted Strings

Formatted strings in Python allow you to include expressions inside string literals, using curly braces {}. These expressions are evaluated at runtime and formatted using the str.format() method or f-strings.

1. str.format() Method

  • Introduced in Python 3.0.
  • You can insert variables or expressions inside the string using {} placeholders.
  • Example:
    name = "Alice"
    greeting = "Hello, {}!".format(name)
    # Output: "Hello, Alice!"
    

2. F-Strings

  • Introduced in Python 3.6, f-strings provide a more concise and readable way to format strings.
  • Prefixed with f or F, variables, or expressions can be placed directly inside the {}.
  • Example:
    name = "Alice"
    greeting = f"Hello, {name}!"
    # Output: "Hello, Alice!"
    

3. Advanced Formatting

  • Both str.format() and f-strings support advanced formatting options, such as specifying width, precision, and alignment.
  • Example:
    value = 3.14159
    formatted = f"Pi is approximately {value:.2f}"
    # Output: "Pi is approximately 3.14"
    

4. Advantages of F-Strings

  • Readability: Easier to read and write, especially for complex expressions.
  • Performance: Generally faster than the str.format() method.

Conclusion: F-strings are the preferred method for string formatting in modern Python due to their simplicity, readability, and efficiency.