new string method in 2.5 (partition)

Jack Diederich jackdied at
Tue Sep 19 22:42:54 CEST 2006

On Tue, Sep 19, 2006 at 07:23:50PM +0000, John Salerno wrote:
> Bruno Desthuilliers wrote:
> > Err... is it me being dumb, or is it a perfect use case for str.split ?
> Hmm, I suppose you could get nearly the same functionality as using 
> split(':', 1), but with partition you also get the separator returned as 
> well.
> > There are IMVHO  much exciting new features in 2.5 (enhanced generators, 
> > try/except/finally, ternary operator, with: statement etc...)
> I definitely agree, but I figure everyone knows about those already. 
> There are also the startswith() and endswith() string methods that are 
> new and seem neat as well.

Partition is much, much nicer than index() or find() for many
(but not all) applications.

diff for parsing "var=X" 
-        i = p.find('=')
-        if i >= 0:
-            name = p[:i]
-            value = p[i+1:]
+        (name, sep_found, value) = p.partition('=')

Notice that preserving the seperator makes for a nice boolean
to test if the partition was successful.  Partition raises an
error if you pass an empty seperator.

parition also has the very desirable feature of returning the orignal
string when the seperator isn't found


script = 'foo.cgi?a=7'
script, sep, params = script.partition('?')

"script" will be "foo.cgi" even if there are no params.  With
find or index you have to slice the string by hand and with split
you would do something like.

    script, params = script.split('?')
  except ValueError: pass


  parts = script.split('?', 1)
  script = parts[0] 
  params = ''.join(parts[1:])

Grep your source for index, find, and split and try rewriting
the code with partition.  Not every instance will turn out cleaner
but many will.



More information about the Python-list mailing list