If you do a join() after a split() using the same delimiter, does this result in the original string?


#1

Question

In the context of this exercise, if you do a join() after a split() using the same delimiter, does this result in the original string?

Answer

Yes, this should result in the original string. This is because join() and split() are essentially inverses of each other.

When we split, it returns a list of substrings that the delimiter was separating. And, when we join on the same delimiter, it merely places that delimiter back where the splits were performed, resulting the same string.

original = "*A*B*C*D"

splitted = original.split("*")
joined = "*".join(splitted)

print(joined) # *A*B*C*D

#2

A lesser known feature of .join() is its ability to work with strings, too.

>>> "*".join('mississippi')
'm*i*s*s*i*s*s*i*p*p*i'
>>> 
>>> ' '.join([chr(x) for x in range(65, 91)])
'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'
>>>