Python split() Method
Description
Python split()Slices the string by the specified delimiter. If the parameter num has a specified value, then num+1 substrings are separated.
Syntax
split() method syntax:
str.split(str="", num=string.count(str)).
Parameters
- str -- Delimiter, defaults to all whitespace characters, including spaces, newlines (\n), tabs (\t), etc.
- num -- Number of splits. Defaults to -1, meaning split all.
Return Value
Returns a list of strings after splitting.
Examples
The following example demonstrates how to use the split() function:
Example (Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( ); # Use space as delimiter, including \n
print str.split(' ', 1 ); # Use space as delimiter, split into two
The output of the above example is as follows:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] ['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
The following example uses # as the delimiter, specifies the second parameter as 1, and returns two parameter lists.
Example (Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
txt = "Google#Example#Taobao#Facebook"
# The second parameter is 1, returns two parameter lists
x = txt.split("#", 1)
print x
The output of the above example is as follows:
['Google', 'Example#Taobao#Facebook']
Other Extensions
Python Strings