Python .join or string concatenation

后端 未结 6 739
小蘑菇
小蘑菇 2021-01-31 18:23

I realise that if you have an iterable you should always use .join(iterable) instead of for x in y: str += x. But if there\'s only a fixed number of va

6条回答
  •  野性不改
    2021-01-31 18:48

    I recommend join() over concatenation, based on two aspects:

    1. Faster.
    2. More elegant.

    Regarding the first aspect, here's an example:

    import timeit    
    
    s1 = "Flowers"    
    s2 = "of"    
    s3 = "War"    
    
    def join_concat():    
        return s1 + " " + s2 + " " + s3  
    
    def join_builtin():    
        return " ".join((s1, s2, s3))    
    
    print("Join Concatenation: ", timeit.timeit(join_concat))         
    print("Join Builtin:       ", timeit.timeit(join_builtin))
    

    The output:

    $ python3 join_test.py
    Join Concatenation:  0.40386943198973313
    Join Builtin:        0.2666833929979475
    

    Considering a huge dataset (millions of lines) and its processing, 130 milliseconds per line, it's too much.

    And for the second aspect, indeed, is more elegant.

提交回复
热议问题