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

后端 未结 16 2707
青春惊慌失措
青春惊慌失措 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:48

    If your python >= 3.6, F-string formatted literal is your new friend.

    It's more simple, clean, and better performance.

    In [1]: params=['Hello', 'adam', 42]
    
    In [2]: %timeit "%s %s, the answer to everything is %d."%(params[0],params[1],params[2])
    448 ns ± 1.48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    In [3]: %timeit "{} {}, the answer to everything is {}.".format(*params)
    449 ns ± 1.42 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    In [4]: %timeit f"{params[0]} {params[1]}, the answer to everything is {params[2]}."
    12.7 ns ± 0.0129 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
    

提交回复
热议问题