Pythonのpartition文字列関数

1107 ワード

2.5版では、rpartitionという関数が新たに追加されました.説明ドキュメントを見てみましょう.
rpartition(...)
    S.rpartition(sep) -> (head, sep, tail)
    
    Search for the separator sep in S, starting at the end of S, and return
    the part before it, the separator itself, and the part after it.  If the
    separator is not found, return two empty strings and S.
(END) 
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.

例を挙げます.
>>> a = 'changzhi1990'
>>> a.rpartition('h')
('changz', 'h', 'i1990')

「h」の左側の文字列、分割子「h」自体、分割子「h」の右側の文字列の3元を返したtupleが見えます.注意:rは右から左へマッチングを表します.
>>> a = 'changzhi1990'
>>> a.partition('h')
('c', 'h', 'angzhi1990')

ここでは左から右にマッチングします.