How does the join( ) method work?



How does the join( ) method work?


.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--!"

FAQ: Learn Python - Battleship - Printing Pretty