Python String split()

Python String.split() is used to split this string by given separator string into specified maximum number of items. split() method returns the parts as a list of strings.

In this tutorial, we will learn the syntax and examples for split() method of String class.

Syntax

The syntax to call split() method on string x in Python is

</>
Copy
x.split(sep, maxsplit)

where

ParameterRequired / OptionalDescription
sepOptionalA string. Specifies the separator using which this string has to be split into parts. Default value is any whitespace is a separator.
maxsplitOptionalA number. Specifies the maximum number of splits that can happen for this string. Default value is -1, meaning no limit on the number of splits.

Examples

In the following program, we take a string 'hello world apple', and split this string using default values for parameters.

Example.py

</>
Copy
x = 'hello world apple'
result = x.split()
print('Original String : ', x)
print('Result List     : ', result)

Output

Original String :  hello world apple
Result List     :  ['hello', 'world', 'apple']

Now, let us specify a separator for split() method. In the following program, we take a string where the items are separated by comma. We shall split this string using separator sep=','.

Example.py

</>
Copy
x = 'hello,world,apple'
result = x.split(sep = ',')
print('Original String : ', x)
print('Result List     : ', result)

Output

Original String :  hello world apple
Result List     :  ['hello', 'world', 'apple']

If we specify the maximum number of splits for the split() method, the number of splits is limited to this number.

In the following example, we specify maxsplit=2. Therefore, the maximum number of splits that happen on this string is 2.

Example.py

</>
Copy
x = 'hello,world,apple,banana,mango'
result = x.split(sep = ',', maxsplit = 2)
print('Original String : ', x)
print('Result List     : ', result)

Output

Original String :  hello,world,apple,banana,mango
Result List     :  ['hello', 'world', 'apple,banana,mango']

Since there are two splits, the original string is split into three parts.

Conclusion

In this Python Tutorial, we learned how to split a string using split() method, with examples.