[Tutor] string codes

Steven D'Aprano steve at pearwood.info
Fri Nov 29 00:45:34 CET 2013


On Wed, Nov 27, 2013 at 10:20:03PM +0100, spir wrote:
> On 11/26/2013 12:59 PM, Steven D'Aprano wrote:
> >On Tue, Nov 26, 2013 at 10:01:14AM +0000, Alan Gauld wrote:
> >
> >>>Is there a method to compare a substring, without building a substring
> >>>from the big one? Like startswith or endswith, but anywhere inside the
> >>>string?
> >>>     test = s[1, -1] == "bcd"    # no!, builds a substring
> >>
> >>I assume you mean  test = s[1:-1] == "bcd"

> Hum, I don't understand the reasoning, here.
> * First, why use the end-index param? (Here in this case, or in any other)? 

Because it matches the example you gave.

You showed an example of slicing a string from the second to the second 
last position, s[1:-1]. That corresponds to start=1 and end=-1.


> It contradicts the idea of starting with in my view, but also is useless 
> for sub-equality checking.

Well I wouldn't say that startswith() is *useless* for checking 
substrings, but it is tricky to get all the arguments right.

> * Second, imagining we'd like to use it anyway, shouldn't it be adjusted 
> according to the lenth of the checked substring? In other words, why do you 
> use '-1'?

Because I copied your example. Your example showed:

-- Take the string s, and look only at the substring starting at 
   position 1 and going to position -1, does it equal "bcd"?

So I did exactly the same thing.


> All in all, startswith plus start-index only seems to work fine, I guess. 
> What is wrong? 

It's not *wrong*, it's a *different question*.

Question 1: 
Does the substring between position i and j *equal* this string?

Question 2:
Does the substring between position i and j *start with* this string?


You started by asking Question 1, solutions using startswith answer 
Question 2. The two questions are only equivalent if the length of the 
shorter string is exactly equal to the length of the substring.



-- 
Steven


More information about the Tutor mailing list