In this article we are going learn about how python split method is used to split the string and produce a list. What is the syntax of python split.
Sometimes we may want to break the long string and convert it into a small segments of strings. Python split is an action opposite to the string concatenation i.e in string concatenation we join multiple strings into one. Whereas using python split we can break the string into required segments.
This purpose can be served using built-in python string split() method. This method breaks the string at specified separator and returns us the list of strings.
Syntax of python split():
string.split([separator [, max-split]])
Python string split() return:
String split() method breaks the string at provided separator and returns the list of strings.
Python string split() arguments:
Python split method has two optional arguments. These arguments decides where to break the string (separator) and maximum number of splits.
- separator: It is a delimiter or character at which the string will be split. Since this is an optional argument so if it is not specified then default characters like white-space or newline will be considered as a separator.
- Characters like white space, any special character like comma or character count can be used as a separator.
- max-split: This argument limits the maximum number of splits. This is also an optional argument and if it is not specified then there will not be any limit on number of splits.
Sample program for python split:
sample_string = 'how are you? John'
# Without separator and Maximum split arguments.
['how', 'are', 'you?', 'John']
# With separator argument i.e "y".
['how are ', 'ou? John']
# With separator ("o") and maximum split arguments ("1").
['h', 'w are you? John']
In above sample python split program, We have split the same string (“How are you? John”) by providing arguments in three different ways.
- In first case we haven’t specified any argument. So in that case split method has considered default arguments i.e white space as a separator and no limit on maximum number of splits.
- In second case we have only provided separator argument as letter “y”. So it has split the string into two parts i.e segment of string before letter “y” and segment after letter “y”.
- In the last case we have provided both the arguments i.e separate (letter “o”) and maximum number of splits (“1”). Though letter “o” is present in the string three times but since we have provided the maximum split number as well so string is broken into two segments only.
Python split have returned us the output list of strings.
Also you can get more help on python forum. Click Here