Difference between Python print/format methods

前端 未结 3 1886
名媛妹妹
名媛妹妹 2020-12-11 04:22

When combining a variable and a string to be printed in Python, there seem to be a number of ways to do the same thing;

test = \"Hello\"
print \"{} World\".f         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-11 04:57

    A little benchmark:

    >>> a = lambda: "{} World".format("Hello")
    >>> b = lambda: "Hello" + " World"
    >>> c = lambda: "%s World" % "Hello"
    >>> d = lambda: "".join(("Hello", " World"))
    >>> a(), b(), c(), d()
    ('Hello World', 'Hello World', 'Hello World', 'Hello World')
    >>> timeit.timeit(a)
    0.7830071449279785
    >>> timeit.timeit(b)
    0.18782711029052734
    >>> timeit.timeit(c)
    0.18806695938110352
    >>> timeit.timeit(d)
    0.3966488838195801
    

    Seems like b and c are fastest, after d, an surprisingly a is slowest.

    But, if you don't do a lot of processing, it doesn't really matter which one to use, just it is better not to mix them.

    I personally prefer "".join for just simple concentenations, and str.format for placing values, like "Hello, my name is {}.".format(name).

    There was a rumor that % formatting will be deprecated and removed in Python 3, but it didn't.

提交回复
热议问题