Python split() method
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
- str -- the delimiter, defaults to all whitespace characters, including spaces, newlines and tabs.
- num -- the number of splits. Defaults to -1, meaning split all.
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
"
;
str
.
split
(
)
;
Using a space as the separator, includes \n
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
)
x
The output of the above example is:
['Google', 'Runoob#Taobao#Facebook']
Python Strings