How does the join( ) method work?


#1

Question

How does the join( ) method work?

Answer

.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
#2

2 posts were split to a new topic: Why is my Code Being Rejected?