.join() command


6/13 battleships.

" ".join()

Can someone please explain what does this command do? i didn't quite get it. How come it removes everything other then the "O"s? Thanks!


It converts a list to a single string.

The board is stored as a list of lists. When we wish to print it, we iterate over the rows, and join all the elements in that row to form a string.

     print " ".join(['O', 'O', 'O', 'O', 'O'])    # O O O O O
# separator ^          list ^                    string ^

The list may not contain non-text values. join() only works with lists of strings. We can use a list comprension to build a tempory list of number to string converted values, and join the temporary list.

a = ''.join([str(x) for x in [1,2,3,4]])
print a    # 1234

Or a little more dynamically...

def num_join(n):
    return ''.join([str(x) for x in n])

a = [1,2,3,4]
print num_join(a)    # 1234


Don't let what follows scare you. It's meant to illustrate how useful .join() can be.

def rot_13(text, bool):
    return ''.join([chr(((ord(x) + (int(bool) or -1) * 13) % 32) + 64 + int(not bool) * 32) if ord(x) != 32 else x for x in text.lower()])


raw_text = "a quick brown fox jumps over the lazy dog"
print raw_text    # a quick brown fox jumps over the lazy dog
b = rot_13(raw_text,True)
print b           # N ^BVPX O_\D[ S\E WBZ]@ \CR_ AUR YNGF Q\T
c = rot_13(b,False)
print c           # a quick brown fox jumps over the lazy dog


Thank you so much! Everything is clear now (: