Python .join or string concatenation

后端 未结 6 696
小蘑菇
小蘑菇 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'm pretty sure all of the people pointing at string formatting are missing the question entirely.)

    Creating a string by constructing an array and joining it is for performance reasons only. Unless you need that performance, or unless it happens to be the natural way to implement it anyway, there's no benefit to doing that rather than simple string concatenation.

    Saying '@'.join([user, host]) is unintuitive. It makes me wonder: why is he doing this? Are there any subtleties to it; is there any case where there might be more than one '@'? The answer is no, of course, but it takes more time to come to that conclusion than if it was written in a natural way.

    Don't contort your code merely to avoid string concatenation; there's nothing inherently wrong with it. Joining arrays is just an optimization.

提交回复
热议问题