1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Python's many ways of string formatting — are the older ones (going to be) deprecated?

Discussão em 'Python' iniciado por Stack, Setembro 18, 2025.

  1. Stack

    Stack Membro Participativo

    Python has at least seven ways of formatting a string:

    In [1]: world = "Earth"

    # method 1a
    In [2]: "Hello, %s" % world
    Out[2]: 'Hello, Earth'

    # method 1b
    In [3]: "Hello, %(planet)s" % {"planet": world}
    Out[3]: 'Hello, Earth'

    # method 2a
    In [4]: "Hello, {0}".format(world)
    Out[4]: 'Hello, Earth'

    # method 2b
    In [5]: "Hello, {planet}".format(planet=world)
    Out[5]: 'Hello, Earth'

    # method 2c
    In [6]: f"Hello, {world}"
    Out[6]: 'Hello, Earth'

    In [7]: from string import Template

    # method 3
    In [8]: Template("Hello, $planet").substitute(planet=world)
    Out[8]: 'Hello, Earth'


    Method 4: template strings.

    A brief history of the different methods:

    • printf-style formatting has been around since Pythons infancy
    • The Template class was introduced in Python 2.4
    • The format method was introduced in Python 2.6
    • f-strings were introduced in Python 3.6
    • t-strings were introduced in Python 3.14

    My questions are:

    • Is printf-style formatting deprecated or going to be deprecated?
    • In the Template class, is the substitute method deprecated or going to be deprecated? (I'm not talking about safe_substitute, which as I understand it offers unique capabilities)

    Similar questions and why I think they're not duplicates:

    See also


    Continue reading...

Compartilhe esta Página