Python3 split() method
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
- str -- the delimiter, defaults to all whitespace characters, including spaces, newlines and tabs.
- num -- the number of splits; if this parameter is set, at most maxsplit+1 substrings are produced. Defaults to -1, meaning split at every occurrence.
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!!!
"
(
str
.
split
(
)
)
Use a space as the default separator
(
str
.
split
(
'
i
'
,
1
)
)
Use i as the separator
(
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
)
(
x
)
The output of the above example is:
['Google', 'Runoob#Taobao#Facebook']
Python3 Strings