Python - String split() Method


Advertisements

The string 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 spliting operation from left side and rsplit() method starts spliting 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.

Example:

In the below example, 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("#"))

Output

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

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

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

['Python Java C++']

String Methods
Advertisements