[Python-Dev] partition() (was: Remove str.find in 3.0?)

BJörn Lindqvist bjourne at gmail.com
Tue Aug 30 17:29:07 CEST 2005


I like partition() but maybe even better would be if strings supported
slicing by string indices.

key, sep, val = 'foo = 32'.partition('=')

would be:

key, val = 'foo = 32'[:'='], 'foo = 32'['=':]

To me it feels very natural to extend Python's slices to string
indices and would cover most of partition()'s use cases. The if sep:
idiom of parition() could be solved by throwing an IndexError: e.g:

_, sep, port = host.partition(':')
if sep:
    try:
        int(port)
    except ValueError:

becomes:

try:
    port = host[':':]
    int(port)
except IndexError:
    pass
except ValueError:

An advantage of using slices would be that you could specify both a
beginning and ending string like this:

>>> s
'http://192.168.12.22:8080'
>>> s['http://':':']
'192.168.12.22'

Sorry if this idea has already been discussed.

-- 
mvh Björn


More information about the Python-Dev mailing list