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

Python3 split() Method

Python3 split() method

Python3 Strings Python3 Strings


Description

The split() method slices a string using a specified delimiter, splitting the string into substrings and returning a list of those substrings.

If the second parameter num has a specified value, the string is split into num+1 substrings.

The split() method is especially useful for breaking a string into parts based on a specific delimiter.

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 3.0+)

#!/usr/bin/python3

str

=

"

this is string example....wow!!!

"

print

(

str

.

split

(

)

)

Use a space as the default separator

print

(

str

.

split

(

'

i

'

,

1

)

)

Use i as the separator

print

(

str

.

split

(

'

w

'

)

)

Use w as the separator

The output of the above example is:


['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']

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

Example (Python 3.0+)

#!/usr/bin/python3

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']

Python3 Strings Python3 Strings