Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does the .join() method do?

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?

like image 987
Matt McCormick Avatar asked Dec 09 '09 19:12

Matt McCormick


People also ask

What join () method does?

Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.

What does join () do in Java?

lang. Thread class provides the join() method which allows one thread to wait until another thread completes its execution.

What does join () do in Python?

The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.

How join () method works internally in Java?

Simply put, How does the join() method of Thread works internally, I know that using join() method you can join one thread at the end of other. For example, if we use thread. join() in main thread, then the main thread should wait until run method of Thread thread finishes completely.


1 Answers

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 
like image 171
Greg Hewgill Avatar answered Oct 24 '22 01:10

Greg Hewgill