Python String split() Method


Contents

Description

The split() method in Python String helps returning a list of all the words present in the string, while making use of the str as the separator which if left unspecified, splits on all whitespace, thereby optionally limiting the total number of splits to num. Thus, one can specify the separator, however, the default separator is any whitespace.

Note: Whenever the maxsplit is specified, then the list would contain the specific number of elements plus one.

Syntax

Here is the syntax for split() method:

str.split(str="", num=string.count(str)).

Parameters

  • str − This represents any delimiter and by default it is space.
  • num − this signifies the number of lines minus one

Return Value

This method in the Python string returns a list of lines.

Example

The example below shows the usage of the split() method.

#!/usr/bin/python

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( )
print str.split(' ', 1 )

When the above program is run, it produces following result:

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.



Navigation
Tutorial
Tutorial
Tutorial