Python Tutorial Python Advanced Python References Python Libraries

Python String - split() Method



The Python split() method is used to split the string into a list. It has two optional parameter which can be used to specify separator for split operation and number of splits.

If the number of split is not provided, this method gives the same result as rsplit(). The only difference between split() and rsplit() methods is that split() method starts splitting operation from left side and rsplit() method starts splitting operation from right side.

Syntax

string.split(separator, max)

Parameters

separator Optional. specify separator character for split operation. default value is whitespace.
max Optional. specify number of split. default value is maximum number of split possible.

Return Value

Returns a list which contains elements as a result of splitting the given string.

Example:

In the example below, split() method is used to split the string into a list. If the specified separator is not found in the string, the split() method returns the whole string as single element of the list.

MyString = "Python Java C++"
print(MyString.split())

MyString = "Python#Java#C++"
print(MyString.split("#"))

MyString = "Python#Java#C++"
print(MyString.split("#", 1))

MyString = "Python Java C++"
print(MyString.split("#"))

The output of the above code will be:

['Python', 'Java', 'C++']
['Python', 'Java', 'C++']
['Python', 'Java#C++']
['Python Java C++']

❮ Python String Methods