Main Content

Python - splitting and joining strings

Archive - Originally posted on "The Horse's Mouth" - 2010-06-16 09:23:35 - Graham Ellis

In Python, you can join a list (or a tuple) of string objects into a single string object, using the join method in the string class. As the join method's in the string class, it has to be called on a string object, and that's the separator that you're putting between each of the joined elements. Thus:

days = ["Monday","Tuesday","Wednesday"]
all = "<br>".join(days)


If I want to split a line of text at a literal string, I specify the complete string as the object on which the split method runs, and then specify the desired separator as a parameter; here are a couple of examples:

say = "This is a line of text"
parts = say.split(" ")
 
first, second = "Tom Smiota".split(" ")
second, first = first, second


That last line is interesting - it's a demonstration of swapping over two variables without the need to specify an intermediate variable - in a standard (previous generation language you might have written:

temp = second
second = first
first = temp


But in Python, a temporary tuple is created to hold both values as you do the transfer, so the coding is shorter and more straightforward.

Python also supports a split method in the re - regular expression - class. It is not polymorphic with the literal string method (i.e. it has a different calling logic / sequence); you specify a regular expression object on which the method is to run, and then you pass in the string to be split as the parameter.

Complete source including the example snippets above - [here] - taken from our Python Programming Training Course.