[Python-ideas] string codes & substring equality
Ethan Furman
ethan at stoneleaf.us
Thu Nov 28 21:50:50 CET 2013
On 11/28/2013 02:53 AM, Steven D'Aprano wrote:
> On Wed, Nov 27, 2013 at 03:52:00PM -0800, Ethan Furman wrote:
>> On 11/27/2013 03:30 PM, Chris Angelico wrote:
>>>
>>> Am I going to check help("".upper) to see if it can
>>> also convert digits to superscript?
>>
>> Heh, that would be cool.
>>
>> I retract (most of) my comment. start(end)swith is certainly not an
>> obvious name for something that can also do random substring comparisons.
>
> startswith and endswith are not suitable for arbitrary substring
> comparisons.
Sure they are. Just do it right. :)
> That same suggestion was made on the tutor list. The OP (Denis) gave an
> example like this:
>
> mystring = "abcde"
> assert mystring[1:-1] == "bcd"
>
> At first glance, using startswith for substring comparisons works fine:
>
> assert mystring.startswith("bcd", 1, -1)
>
> but alas startswith does the wrong thing:
>
> astr = "abcdefghijklmnopqrstuvwxyz"
> astr.startswith("bcd", 1, -1) == (astr[1:-1] == "bcd")
> => returns False
Which simply shows an easy mistake to make. The proper way, if using startswith (or endswith) is to be careful of the
length of both pieces.
--
~Ethan~
More information about the Python-ideas
mailing list