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

前端 未结 5 1953
自闭症患者
自闭症患者 2020-11-22 07:01

Python has at least six ways of formatting a string:

In [1]: world = \"Earth\"

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

# method          


        
5条回答
  •  不知归路
    2020-11-22 07:21

    The % operator for string formatting is not deprecated, and is not going to be removed - despite the other answers.
    Every time the subject is raised on Python development list, there is strong controversy on which is better, but no controversy on whether to remove the classic way - it will stay. Despite being denoted on PEP 3101, Python 3.1 had come and gone, and % formatting is still around.

    The statements for the keeping classic style are clear: it is simple, it is fast, it is quick to do for short things. Using the .format method is not always more readable - and barely anyone - even among the core developers, can use the full syntax provided by .format without having to look at the reference Even back in 2009, one had messages like this: http://mail.python.org/pipermail/python-dev/2009-October/092529.html - the subject had barely showed up in the lists since.

    2016 update

    In current Python development version (which will become Python 3.6) there is a third method of string interpolation, described on PEP-0498. It defines a new quote prefix f"" (besides the current u"", b"" and r"").

    Prefixing a string by f will call a method on the string object at runtime, which will automatically interpolate variables from the current scope into the string:

    >>> value = 80
    >>> f'The value is {value}.'
    'The value is 80.'
    

提交回复
热议问题