Python String split() Method

The split() method splits the string from the specified separator and returns a list object with string elements. The default separator is any whitespace character such as space, \t, \n, etc.

Syntax:

str.split(separator, maxsplit)

Parameters:

  1. separator: (optional) The delimiter string. The default separator is any whitespace character such as space, \t, \n, etc.
  2. maxsplit: (optional) Defines the maximum number of splits that can be done. Thus, the list can contain at most maxsplit + 1 elements. The default maxsplit is -1 that means unlimited splits.

Return Value:

Returns a list object with string elements.

The following example demonstrates the simple use of the split() method.

Example: Split a String with Default Whitespace Chars
mystr = 'Hello World'
print(mystr.split())

print('Hello     World'.split())
print('Hello\tWorld'.split())
print('Hello\nWorld'.split())
print('Hello\u2028World'.split())
Output
['Hello', 'World']
['Hello', 'World']
['Hello', 'World']
['Hello', 'World']
['Hello', 'World']

In the above example, all the string splits at the default whitespace characters such as ' ', '    ', '\t', and '\n' and returns a list ['Hello', 'World']. Even it splits at the Unicode char of line separator '\u2028'.

The following examples specifies the separator.

Example: Split using Separator
langs = 'C,Python,R,Java,SQL,Hadoop'
print(langs.split(','))

fruits = 'apples$banana$mango$fig$pear'
print(fruits.split('$'))
Output
['C', 'Python', 'R', 'Java', 'SQL', 'Hadoop']
['apples', 'banana', 'mango', 'fig','pear']

In the above example, the langs.split(',') specifies a comma , as a separator and fruits.split('$') specifies the $ symbol as a separator. So, the split() method will split a string at each separator and include each part of a string in a list.

If the specified seperator does not exist, then it returns a list with the whole string as an element.

Example: Split using Separator
langs = 'C,Python,R,Java,SQL,Hadoop'
print(langs.split('@'))
Output
['C,Python,R,Java,SQL,Hadoop']
Note:
The split() method will raise the ValueError if a separator is an empty string ''.

The following example limits the split by specifying the maxsplit parameter.

Example: Split using Separator
langs = 'C,Python,R,Java,SQL,Hadoop'
print(langs.split(',', 3))

fruits = 'apples$banana$mango$fig$pear'
print(fruits.split('$', 2))
Output
['C', 'Python', 'R', 'Java,SQL,Hadoop']
['apples', 'banana', 'mango$fig$pear']

In the above example, the langs.split(',', 3) specifies 3 as maxsplit argument, so it will split langs string 3 times and so a list object includes four element. The fourth element is the remaining string. In the same way, the fruits.split('$', 2) will be split maximum of two times, and the returned list will include three elements.