Python .join or string concatenation

后端 未结 6 698
小蘑菇
小蘑菇 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 19:02

    I'll just note that I've always tended to use in-place concatenation until I was rereading a portion of the Python general style PEP PEP-8 Style Guide for Python Code.

    • Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Pyrex, Psyco, and such). For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a+=b or a=a+b. Those statements run more slowly in Jython. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

    Going by this, I have been converting to the practice of using joins so that I may retain the habit as a more automatic practice when efficiency is extra critical.

    So I'll put in my vote for:

    ret = '@'.join([user, host])
    

提交回复
热议问题