THE JOIN() FUNCTION
Another way to remove extraneous spaces is to use the join() function:
text1 = ' there are extra spaces '
print('text1:',text1)
text2 = ' '.join(text1.split())
print('text2:',text2)
text2 = 'XYZ'.join(text1.split())
print('text2:',text2)
The split() function “splits” a text string into a set of words, and also removes the extraneous white spaces. Next, the join() function “joins” together the words in the string text1, using a single white space as the delimiter. The last code portion of the preceding code block uses the string XYZ as the delimiter instead of a single white space. The output of the preceding code block is as follows:
text1: there are extra spaces
text2: there are extra spaces
text2: thereXYZareXYZextraXYZspaces...