现在的位置: 首页 > 综合 > 正文

字符串分割(split 方法)

2013年10月12日 ⁄ 综合 ⁄ 共 806字 ⁄ 字号 评论关闭

帮助:

>>> help(str.split)
Help on method_descriptor:
 
split(...)
    S.split([sep[, maxsplit]]) -> list of strings
    
    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.

测试代码:

>>> a_str = '1#2#3#4#5#6#7'
>>> a_str.split('#')
['1', '2', '3', '4', '5', '6', '7']
>>> a_str.split('#', 1)
['1', '2#3#4#5#6#7']
>>> a_str.split('#', 2)
['1', '2', '3#4#5#6#7']
>>> a_str.split('#', 3)
['1', '2', '3', '4#5#6#7']
>>> a_str.split('#', 4)
['1', '2', '3', '4', '5#6#7']
>>> a_str.split('#', 5)
['1', '2', '3', '4', '5', '6#7']
>>> a_str.split('#', 6)
['1', '2', '3', '4', '5', '6', '7']

参数说明:

sep:分隔符,表示从字符串什么地方对其进行分隔;

maxsplit:表示把字符串分割到哪个分隔符(从字符串最左边开始,第一个分隔符的位置是1)指示的位置为止,这里 maxsplit 指示的那个位置是最后一个要分隔的地方。

注:

如果空参数调用 split,则分隔符是任何空白字符(whitespace,空格,Tab,或多个的联合)。

抱歉!评论已关闭.