Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python split() method

Python split() method

Python Strings Python Strings


Description

Python split() Splits a string by a specified separator. If the parameter num is specified, the string is split into num+1 substrings.

Syntax

Syntax of the split() method:


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

Parameters

Return Value

Returns a list of the split substrings.

Example

The following example shows how to use the split() function:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

str

=

"

Line1-abcdef

\n

Line2-abc

\n

Line4-abcd

"

;

print

str

.

split

(

)

;

Using a space as the separator, includes \n

print

str

.

split

(

'

'

,

1

)

;

Using a space as the separator, split into two

The output of the above example is:


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

The following example uses # as the separator and sets the second parameter to 1, returning a list of two items.

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

txt

=

"

Google#Runoob#Taobao#Facebook

"

The second parameter is 1, so a list of two elements is returned

x

=

txt

.

split

(

"

"

,

1

)

print

x

The output of the above example is:

['Google', 'Runoob#Taobao#Facebook']

Python Strings Python Strings