Python String Split

Python string split() method is used to split string by a character, space or comma into a list of words or characters. By default string splits by space as delimiter.

Python String Split() Method

To split a string into a list in python we can use split() method.

Example 1

This example splits a string into a list which contains words of string as list items.
some_String = "I am learning python"

word_List = some_String.split()

print(word_List)

''' Output of above code:- 

['I', 'am', 'learning', 'python']

'''
The split() method splits a string into a list. In our example above it split some_String into a word list. But we can specify from where to split the string.

Parameters of split() method

sep

The separator argument is used for this purpose. The default value for this separator argument is any whitespace.

maxsplit

Another argument we can pass to split() method is maxsplit, if specified, the list will contain the specified number of elements plus one. Default value for max is -1, which means for all occurrences.

Both sep and maxsplit are optional arguments of split() method.

Syntax of Split() Method

string. split([sep[, maxsplit]])

Return Value

split() method returns a list.

Example 2 using separator argument

If separator is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings as shown in the example below

>>> '10,,20'.split(',')
rturns [‘10’, ‘’, ‘20’]). The sep argument ma consist of multiple characters (for example,

>>> '10<>20<>30'.split('<>')
returns [‘10’, ‘20’, ‘30’]). Splitting an empty string with a specified separator returns [‘’].

Read the docs - official