[Python-ideas] string codes & substring equality

spir denis.spir at gmail.com
Thu Nov 28 13:50:45 CET 2013


On 11/28/2013 11:53 AM, Steven D'Aprano wrote:
> but alas startswith does the wrong thing:
>
> astr = "abcdefghijklmnopqrstuvwxyz"
> astr.startswith("bcd", 1, -1) == (astr[1:-1] == "bcd")
> => returns False

Sorry, it works fine (I still don't understand your reasoning, Steven). You are 
here using a wrong end-index (-1). And anyway there is no question of end-index 
in substr comparison for equality, it's just the substring size.

If you really want to use this second index for some reason I find myself unable 
to guess, a right way would be, I think:

ss, i, n = "bcd", 1, len("bcd")
astr.startswith(ss, i, i+n) == (astr[i:i+n] == ss)

spir at ospir:~$ python3
Python 3.3.1 (default, Sep 25 2013, 19:29:01)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> astr = "abcdefghijklmnopqrstuvwxyz"
>>> ss, i, n = "bcd", 1, len("bcd")
>>> astr.startswith(ss, i, i+n) == (astr[i:i+n] == ss)
True

Denis


More information about the Python-ideas mailing list