What exactly does the .join() method do?

Matt McCormick picture Matt McCormick · Dec 9, 2009 · Viewed 564.8k times · Source

I'm pretty new to Python and am completely confused by .join() which I have read is the preferred method for concatenating strings.

I tried:

strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring().join(strid)

and got something like:

5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5

Why does it work like this? Shouldn't the 595 just be automatically appended?

Answer

Greg Hewgill picture Greg Hewgill · Dec 9, 2009

Look carefully at your output:

5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
^                 ^                 ^

I've highlighted the "5", "9", "5" of your original string. The Python join() method is a string method, and takes a list of things to join with the string. A simpler example might help explain:

>>> ",".join(["a", "b", "c"])
'a,b,c'

The "," is inserted between each element of the given list. In your case, your "list" is the string representation "595", which is treated as the list ["5", "9", "5"].

It appears that you're looking for + instead:

print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid