Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python .join or string concatenation

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 variables that aren't already in an iterable, is using .join() still the recommended way?

For example I have

user = 'username' host = 'host' 

should I do

ret = user + '@' + host 

or

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

I'm not so much asking from a performance point of view, since both will be pretty trivial. But I've read people on here say always use .join() and I was wondering if there's any particular reason for that or if it's just generally a good idea to use .join().

like image 886
Falmarri Avatar asked Nov 12 '10 16:11

Falmarri


People also ask

What is the best way to concatenate strings in Python?

Even though there're multiple ways to concatenate strings in Python, it's recommended to use the join() method, the + operator, and f-strings to concatenate strings.

How do you concatenate a list of strings in Python?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

Is concatenation faster than join?

Doing N concatenations requires creating N new strings in the process. join() , on the other hand, only has to create a single string (the final result) and thus works much faster.

Can you concatenate strings in Python?

In Python, you can concatenate two different strings together and also the same string to itself multiple times using + and the * operator respectively.


1 Answers

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.

like image 76
Thomas Wouters Avatar answered Sep 19 '22 12:09

Thomas Wouters