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

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

    Python 3.6.7 comparative:

    #!/usr/bin/env python
    import timeit
    
    def time_it(fn):
        """
        Measure time of execution of a function
        """
        def wrapper(*args, **kwargs):
            t0 = timeit.default_timer()
            fn(*args, **kwargs)
            t1 = timeit.default_timer()
            print("{0:.10f} seconds".format(t1 - t0))
        return wrapper
    
    
    @time_it
    def new_new_format(s):
        print("new_new_format:", f"{s[0]} {s[1]} {s[2]} {s[3]} {s[4]}")
    
    
    @time_it
    def new_format(s):
        print("new_format:", "{0} {1} {2} {3} {4}".format(*s))
    
    
    @time_it
    def old_format(s):
        print("old_format:", "%s %s %s %s %s" % s)
    
    
    def main():
        samples = (("uno", "dos", "tres", "cuatro", "cinco"), (1,2,3,4,5), (1.1, 2.1, 3.1, 4.1, 5.1), ("uno", 2, 3.14, "cuatro", 5.5),) 
        for s in samples:
            new_new_format(s)
            new_format(s)
            old_format(s)
            print("-----")
    
    
    if __name__ == '__main__':
        main()
    

    Output:

    new_new_format: uno dos tres cuatro cinco
    0.0000170280 seconds
    new_format: uno dos tres cuatro cinco
    0.0000046750 seconds
    old_format: uno dos tres cuatro cinco
    0.0000034820 seconds
    -----
    new_new_format: 1 2 3 4 5
    0.0000043980 seconds
    new_format: 1 2 3 4 5
    0.0000062590 seconds
    old_format: 1 2 3 4 5
    0.0000041730 seconds
    -----
    new_new_format: 1.1 2.1 3.1 4.1 5.1
    0.0000092650 seconds
    new_format: 1.1 2.1 3.1 4.1 5.1
    0.0000055340 seconds
    old_format: 1.1 2.1 3.1 4.1 5.1
    0.0000052130 seconds
    -----
    new_new_format: uno 2 3.14 cuatro 5.5
    0.0000053380 seconds
    new_format: uno 2 3.14 cuatro 5.5
    0.0000047570 seconds
    old_format: uno 2 3.14 cuatro 5.5
    0.0000045320 seconds
    -----
    

提交回复
热议问题