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

Python的partition字符串函数

2018年08月16日 ⁄ 综合 ⁄ 共 648字 ⁄ 字号 评论关闭

在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')

可以看到返回了一个三元的tuple,分别是‘h’ 的左边的字符串,分割符‘h’本身,和分割符‘h’的右边的字符串。注意:r 代表从右向左开始匹配。

>>> a = 'changzhi1990'
>>> a.partition('h')
('c', 'h', 'angzhi1990')

这里是从左到右开始匹配的。

抱歉!评论已关闭.