Python Split and Join Examples

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'])

One Response to Python Split and Join Examples

  1. Finally! I have been looking for this all day!!!!!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Go back to top