.join() is another method available to strings. It works by attaching it to a string, like ” “ (a space), and then telling it what to “join” with that string between each element.
So when we use it with a list, it separates each item in the list by the string you attached it to and creates a single string result. Take a look at the example below:
my_greeting = ["Hello", "coder", "people", "!"] # Note: there are no spaces
print " ".join(my_greeting) # Prints "Hello coder people !"
print "--".join(my_greeting) # Prints "Hello--coder--people--!"
This function gave me a hard time yesterday!
I wish it was something like this instead: join(" ", list). Yes, I know I could probably create a custom function for that, but that’s not the point when I sitll have to learn the syntax of this function which is kinda unusual one for me.
That would make it a built-in rather than a str method. The inner workings would be more complex, thus less optimized.
By writing .join() as a method of the str class, the interpreter does very little of the validation work. If we try to call the method on anything other than a str it will raise an AttributeError telling us that the object does not have a ‘join’ attribute. If we try to pass any object that is not iterable it will raise a TypeError since the method can only join an iterable.
The above describes a separation of concerns, one handled by the interpreter, the other by the method’s own error trapping.
Once you gain familiarity with the many built in classes and their associated methods, you’ll find the language very intuitive. Think of it as leaning how to use an HP calculator after having spent years working with a TI. Reverse Polish Notation takes some getting used to, but once we do, we love it. (Mind, millennials might not be familiar with either.)