Story Details

  • Python's new t-strings

    Posted: 2025-04-21 04:31:35

    Python 3.12 introduces "t-strings," a new string literal type designed for templating. Prepending a string with t (e.g., t"Hello {name}") signifies a t-string, which supports delayed interpolation and formatting. Unlike f-strings, t-strings don't immediately evaluate expressions within braces. Instead, they create a reusable template that can be formatted later using the .format() method. This allows for constructing templates separately from their data, improving code organization and enabling scenarios like dynamic template creation or translation. T-strings also offer enhanced control over formatting via format specifiers within the braces, similar to existing str.format() functionality. While sharing some similarities with f-strings, t-strings prioritize reusability and deferred evaluation, providing a powerful alternative for template-based string construction.

    Summary of Comments ( 212 )
    https://news.ycombinator.com/item?id=43748512

    Hacker News users generally expressed enthusiasm for Python's proposed t-strings (trimmed strings), viewing them as a valuable addition for template literals and multiline strings. Several commenters highlighted the potential for improved readability and maintainability, especially when dealing with SQL queries or HTML. Some discussed the syntax, suggesting alternatives and pondering potential edge cases and implementation details, like handling backslashes. A few pointed out the existing workarounds available and questioned whether this feature warranted inclusion in the core language, given the learning curve it might introduce for new users. There was also some discussion comparing t-strings to similar features in other languages, like C#'s verbatim strings and JavaScript's template literals.