Python string split examples

Python has in-built string split function which can be used to split a string on any delimiter and return a python list (array). If no delimiter is specified then it uses in built algorithm to split on all whitespace character sequence. Here are some examples.

Split string on space

## 2 spaces between python and world
s = "Hello python  world"
a = s.split(' ')
print a
['Hello', 'python', '', 'world']
Env: Python 2.7.6

Split string on space with max split limit

Note that a split limit of 2 will result in max 3 elements in array.

s = "Hello python world again"
a = s.split(' ', 2)
print a
['Hello', 'python', 'world again']
Env: Python 2.7.6

Split string without delimiter

Without delimiter python splits string on whitespace sequence (considering all contiguous whitespace as one). It is better to specify the delimiter explicitly though.

## string with multiple spaces and newline
s = "Hello  python world\nagain"
a = s.split()
print a
['Hello', 'python', 'world', 'again']
Env: Python 2.7.6

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments