In this lesson we will learn about Python split method for string which is an important method for extracting words from a string based on a string separator.
Python split Method
Python’s split() method returns a list of all the words in the string, using its seperatorString as the separator ( if undefined then it will split the string for all the white-spaces ).
Syntax
The string for Python split method is :
string.split( seperatorString [, lines )]
- seperatorString – This parameter takes the separation string which will be used for splitting the string. The default value for this is Space.
- lines – The number of lines to be made. This parameter is optional.
Example
Here are some examples regarding Python split method:
myString = "My favorite fruits are Apple, Orange, Banana, Grape." print myString.split( ) print myString.split( ',' ) print myString.split( ',' , 2 )
The output will be like:
# Output for myString.split( ) ['My', 'favorite', 'fruits', 'are', 'Apple,', 'Orange,', 'Banana,', 'Grape.'] # Output for myString.split( ',' ) ['My favorite fruits are Apple', ' Orange', ' Banana', ' Grape.'] # Output for myString.split( ',' , 2 ) ['My favorite fruits are Apple', ' Orange', ' Banana, Grape.']
You can also have a look at some other Python tutorials which will be helpful:
The post Python split Method for String appeared first on JS Tricks.