String formatting: % vs. .format vs. string literal

后端 未结 16 2706
青春惊慌失措
青春惊慌失措 2020-11-21 04:18

Python 2.6 introduced the str.format() method with a slightly different syntax from the existing % operator. Which is better and for what situations?

Pyt

16条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 04:49

    As of Python 3.6 (2016) you can use f-strings to substitute variables:

    >>> origin = "London"
    >>> destination = "Paris"
    >>> f"from {origin} to {destination}"
    'from London to Paris'
    

    Note the f" prefix. If you try this in Python 3.5 or earlier, you'll get a SyntaxError.

    See https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings

提交回复
热议问题