How to use Python split method

The Python Split() string methods is one of the workhorses of programming and is used extensively in text processing. The method splits a sentence or string into individual words and returns it as a list.

>>> sentence = 'Somewhere, something incredible is waiting to be known.'
>>> sentence.split()
['Somewhere,', 'something', 'incredible', 'is', 'waiting', 'to', 'be', 'known.']

The method also take a ‘sep’ argument which allows you to define the separator in the original string. Default is a space as in the example below, but can be other characters.

>>> csv_header = 'name:address:phone:email'
>>> csv_header.split(':')
['name', 'address', 'phone', 'email']

If ‘maxsplit’ parameter is given, at most maxsplit splits are done, the resulting list will have at most maxsplit+1 elements. If maxsplit is not specified or -1 is specified, then there is no limit on the number of splits.

>>> csv_header = 'name:address:phone:email'
>>> csv_header.split(':',1)
['name', 'address:phone:email']
>>> csv_header.split(':',2)
['name', 'address', 'phone:email']
>>> csv_header.split(':',3)
['name', 'address', 'phone', 'email']
>>> csv_header.split(':',-1)
['name', 'address', 'phone', 'email']

Note that the split starts from the left, if you want to start it from right you can use the rsplit() method, which works just like the split() method but starts from the right.

>>> csv_header = 'name:address:phone:email'
>>> csv_header.rsplit(':',1)
['name:address:phone', 'email']
>>> csv_header.rsplit(':',2)
['name:address', 'phone', 'email']
>>> csv_header.rsplit(':',3)
['name', 'address', 'phone', 'email']

Leave a Reply

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