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'
del.icio.us Digg Furl Reddit Ma.gnolia RawSugar Shadows Spurl StumbleUpon Tailrank Technorati

Tags: Python

RSS feed | Trackback URI

Comments »

No comments yet.

Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line=""> in your comment.

Article Categories

Recent Articles

Recommended

Feeds