How to split a string in Python

PythonServer Side ProgrammingProgramming

Manytimes we need to split a given string into multiple parts based on some delimiter. Python provides a function named split() which can be used to achieve this. It also provides a way to control the delimiter and number of characters to be considered as delimiter.


In the below example we a string containing many words and space in between. But there are two space characters between Banana and grape. Accordingly the split happens. When no parameter is supplied each space is taken as a delimiter.

 Live Demo

str = "Apple Banana Grapes Apple";
print(str.split(' ', 2))


Running the above code gives us the following result −

['Apple', 'Banana', 'Grapes', 'Apple']
['Apple', 'Banana', ' Grapes Apple']
Published on 23-Aug-2019 16:08:50