Addition to slice syntax (for strings)
Skip Montanaro
skip at pobox.com
Mon Sep 13 14:01:39 EDT 2004
>>>>> "Will" == Will McGugan <news at NOwillmcguganSPAM.com> writes:
Will> I'd like to suggest an addition to the slice syntax. How about
Will> allowing strings as arguments to slices on strings, and interpret
Will> them as the index of the substring found within the string being
Will> sliced. I'm sure I didnt explain that too well, so here is an
Will> example..
How would you interpret
>>> s = "my dog has fleas"
>>> s['x':'z'] # both strings nonexistent
>>> s['z':'f'] # first string nonexistent
>>> s['f':'z'] # second string nonexistent
>>> s['g':'d'] # second appears earlier than first
Returning the empty string in all cases is plausible, but other
possibilities make sense at some level:
s['x':'z'] => ""
s['x':'z'] => "my dog has fleas"
s['z':'f'] => "my dog has f"
s['z':'f'] => "my dog has "
s['f':'z'] => "leas"
s['f':'z'] => "fleas"
s['g':'d'] => ""
s['g':'d'] => "god"
Two other quibbles about your example:
* why not use s.rfind("...") instead of s.find("...") for the second
index?
* why add 1 to the offset of the second index?
In short, there is enough uncertainty in what the "right" thing to do is, I
suspect you'd be better off just subclassing strings when you need this sort
of functionality in your apps.
Skip
More information about the Python-list
mailing list