Python .join or string concatenation

后端 未结 6 689
小蘑菇
小蘑菇 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:54

    If you're creating a string like that, you normally want to use string formatting:

    >>> user = 'username'
    >>> host = 'host'
    >>> '%s@%s' % (user, host)
    'username@host'
    

    Python 2.6 added another form, which doesn't rely on operator overloading and has some extra features:

    >>> '{0}@{1}'.format(user, host)
    'username@host'
    

    As a general guideline, most people will use + on strings only if they're adding two strings right there. For more parts or more complex strings, they either use string formatting, like above, or assemble elements in a list and join them together (especially if there's any form of looping involved.) The reason for using str.join() is that adding strings together means creating a new string (and potentially destroying the old ones) for each addition. Python can sometimes optimize this away, but str.join() quickly becomes clearer, more obvious and significantly faster.

提交回复
热议问题