Q. Explain function split () with example.

or

Q. What is the function of split() method?


Answer:-

split():- The split() method breaks up a string at the specified separator and returns a list of sub-strings.

Syntax:

str.split([separator [, maxsplit]])

The split() method takes a maximum of 2 parameters:

separator (optional):- The separator is a delimiter. The string splits at the specified separator. If the separator is not specified, any white space (space, newline, etc.) string is a separator.

maxsplit (optional):- The maxsplit defines the maximum number of splits. The default value of maxsplit is -1, which means no limit on the number of splits.

For example:-

>>> x= 'blue; red; green'
>>> x.split(";")
['blue', 'red', 'green']
>>> text = 'Love your country'
>>> print (text.split())
['Love', 'your', 'country']

• Here, separator is not specified and, by default, space is a string separator.

The second argument 'maxsplit' is optional and its default value is zero. If an integer value 'n' is given for the second argument, the string is split into 'n+1' strings.

For example:-

>>> grocery = 'Red: Blue: Orange: Pink'
>>>print (grocery.split(':', 2))
['Red', 'Blue', 'Orange: Pink']
>>> print (grocery.split(':',1)) #maxsplit is 1
['Red', 'Blue: Orange: Pink']
>>> print (grocery.split(':',5))
['Red', 'Blue', 'Orange', 'Pink']
>>> print (grocery.split(':',0)) #maxsplit is 0, so it will return the string
['Red: Blue:Orange: Pink']
>>>

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post