Overview of F-Strings Introduced in Python 3.6, f-strings (formatted string literals) revolutionized how we handle string interpolation. They provide a concise, readable, and highly performant way to embed expressions inside string literals. By prefixing a string with `f` or `F`, you can use curly braces `{}` to evaluate Python expressions directly within the string. This method has largely superseded older techniques like the `%` operator or the `.format()` method due to its cleaner syntax and superior execution speed. Prerequisites Before diving into advanced formatting, you should have a basic understanding of Python variables and data types. Familiarity with classes and dictionaries will help you grasp object representation and expression evaluation within strings. You will need Python version 3.6 or higher installed to use this feature. Key Libraries & Tools - **datetime**: A built-in Python module used for manipulating dates and times, which f-strings can format using specific codes. - **pendulum**: A third-party library that offers more intuitive and human-friendly date and time management than the standard library. - **timeit**: A tool for measuring the execution time of small code snippets, used here to prove f-string performance superiority. Number Formatting and Precision F-strings provide a mini-language for number formatting that handles everything from binary conversion to financial rounding. To format a number, use a colon `:` after the variable name. ```python price = 100.2356 print(f"Amount: {price:.2f}") # Output: 100.24 (rounds to 2 decimal places) large_sum = 44000000000 print(f"Cost: ${large_sum:,}") # Output: 44,000,000,000 (thousands separator) ``` You can also handle percentages and scientific notation with ease. For instance, `{val:.1%}` converts `0.556` into `55.6%`. If you need to pad numbers with leading zeros for file naming or accounting, use `{number:06}` to ensure a total width of six characters, filled with zeros. Padding, Alignment, and Objects Alignment is critical for creating clean terminal outputs or logs. F-strings use `<`, `>`, and `^` for left, right, and center alignment, respectively. ```python greeting = "Hi" print(f"{greeting:_^10}") # Output: ____Hi____ ``` When working with custom objects, f-strings default to the `__str__` method. However, you can force the use of `__repr__` (the developer-friendly version) by appending `!r`. This is incredibly useful for debugging when you need to see the exact state of an object rather than its formatted string output. Syntax Notes - **Double Braces**: To print literal curly braces in an f-string, you must double them: `{{` and `}}`. - **Quotes**: If your expression contains strings, ensure you use different quote types for the expression and the f-string itself to avoid syntax errors. - **No Comments**: You cannot include `#` comments inside the expression braces `{}`. Practical Examples and Performance One of the most powerful features added in Python 3.8 is the `=` specifier for self-documenting expressions. Writing `f"{x=}"` outputs `x=10` if `x` is 10, which saves significant time during debugging. Performance benchmarks using the timeit module reveal that f-strings are significantly faster than older methods. They are approximately twice as fast as `%` formatting and `.format()` because they are evaluated at runtime as part of the constant folding process rather than being parsed as a constant string with subsequent function calls. This makes them the best choice for high-frequency logging or large-scale data processing.
timeit
Libraries
Sep 2022 • 1 videos
High activity month for timeit. ArjanCodes among the most active voices, with 1 videos across 1 sources.
Sep 2022
- Sep 9, 2022