天天看点

Python之字符串方法split()与partition()

string中的split()方法

字符串中的split()方法定义如下:

str.split = split(...)
    S.split(sep=None, 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.
           

给定分隔符(所有的字符都算是分隔符,包括空格)时,split()返回list of strings,返回的list中不包含分割符。不设定分割符时,split()以空格(连续的空格当作一个空格)作为分隔符。此外split()还可以设定分割的数次。

实例1(不设分隔符):

"\n\nhello\t\t world \n\n\n My name is Dong".split(None,2)
['hello', 'world', 'My name is Dong']
>>> "\n\nhello\t\t world \n\n\n My name is Dong".split(None,3)
['hello', 'world', 'My', 'name is Dong']
>>> "\n\nhello\t\t world \n\n\n My name is Dong".split(None,4)
['hello', 'world', 'My', 'name', 'is Dong']
           

实例2(以空格作为分隔符与不设分隔符时的对比)

>>> "\n\nhello\t\t world \n\n\n My name is Dong".split(' ',2)
['\n\nhello\t\t', 'world', '\n\n\n My name is Dong']
>>> "\n\nhello\t\t world \n\n\n My name is Dong".split(None,2)
['hello', 'world', 'My name is Dong']
           

string中的partition()方法

字符串中partition()方法定义如下:

str.partition = partition(...)
    S.partition(sep) -> (head, sep, tail)

    Search for the separator sep in S, and return the part before it,
    the separator itself, and the part after it.  If the separator is not
    found, return S and two empty strings.
           

与split()不同的是,partition()返回的是分隔符前的字符串,分割符,以及分隔符后的字符串组成的元组。如果字符串中不包含该分隔符,则返回该字符串以及两个空字符串,partition必须设有分隔符,而且只是分割一次。

实例1

>>> "\n\nhello\t\t world \n\n\n My name is Dong".partition("\t")
('\n\nhello', '\t', '\t world \n\n\n My name is Dong')
>>> "\n\nhello\t\t world \n\n\n My name is Dong".partition()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: partition() takes exactly one argument (0 given)
>>> "\n\nhello\t\t world \n\n\n My name is Dong".partition("dsaa")
('\n\nhello\t\t world \n\n\n My name is Dong', '', '')
>>> 
           

仅此说明下split()与partition()的不同。

为了自由而努力学习。