new string method in 2.5 (partition)

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Sep 19 21:32:21 CEST 2006


John Salerno a écrit :
> Forgive my excitement, especially if you are already aware of this, but 
> this seems like the kind of feature that is easily overlooked (yet could 
> be very useful):
> 
> 
> Both 8-bit and Unicode strings have new partition(sep) and 
> rpartition(sep) methods that simplify a common use case.
> The find(S) method is often used to get an index which is then used to 
> slice the string and obtain the pieces that are before and after the 
> separator.

Err... is it me being dumb, or is it a perfect use case for str.split ?

> partition(sep) condenses this pattern into a single method 
> call that returns a 3-tuple containing the substring before the 
> separator, the separator itself, and the substring after the separator. 
> If the separator isn't found, the first element of the tuple is the 
> entire string and the other two elements are empty. rpartition(sep) also 
> returns a 3-tuple but starts searching from the end of the string; the 
> "r" stands for 'reverse'.
> 
> Some examples:
> 
> 
>  >>> ('http://www.python.org').partition('://')
> ('http', '://', 'www.python.org')
>  >>> ('file:/usr/share/doc/index.html').partition('://')
> ('file:/usr/share/doc/index.html', '', '')
>  >>> (u'Subject: a quick question').partition(':')
> (u'Subject', u':', u' a quick question')
>  >>> 'www.python.org'.rpartition('.')
> ('www.python', '.', 'org')
>  >>> 'www.python.org'.rpartition(':')
> ('', '', 'www.python.org')

I must definitively be dumb, but so far I fail to see how it's better 
than split and rsplit:

 >>> 'http://www.python.org'.split('://')
['http', 'www.python.org']
 >>> 'file:/usr/share/doc/index.html'.split('://')
['file:/usr/share/doc/index.html']
 >>> u'Subject: a quick question'.split(': ')
[u'Subject', u'a quick question']
 >>> u'Subject: a quick question'.rsplit(': ')
[u'Subject', u'a quick question']
 >>> 'www.python.org'.rsplit('.', 1)
['www.python', 'org']
 >>>

There are IMVHO  much exciting new features in 2.5 (enhanced generators, 
try/except/finally, ternary operator, with: statement etc...)



More information about the Python-list mailing list