Python Split and Join Examples
January 26th, 2009
Split and join in python are similar to the equivalent functions in most dynamic languages with a few minor differences:
Python Split
Split a sentence into separate words:
sentence = "the cat sat on the mat" print sentence.split() ['the', 'cat', 'sat', 'on', 'the', 'mat']
Split words separated by a single character:
sentence = "the,cat,sat,on,the,mat" print sentence.split(',') ['the', 'cat', 'sat', 'on', 'the', 'mat']
Split words separated by a string:
sentence = "theSPACEcatSPACEsatSPACEonSPACEtheSPACEmat" print sentence.split('SPACE') ['the', 'cat', 'sat', 'on', 'the', 'mat']
Split only the first two words in a comma separated string
sentence = "the,cat,sat,on,the,mat" print sentence.split(',',2) ['the', 'cat', 'sat,on,the,mat']
Python Join
Join uses a sligthly difference implmentation to what you might be used to. The character that joins the elements is the one upon which the function is called
Joining an array with spaces
>>> ' '.join(['the', 'cat', 'sat', 'on', 'the', 'mat']) 'the cat sat on the mat'
Joining an array with commas
>>> ','.join(['the', 'cat', 'sat', 'on', 'the', 'mat']) 'the,cat,sat,on,the,mat'
Tags: Python
No comments yet.