[Tutor] string codes

Steven D'Aprano steve at pearwood.info
Tue Nov 26 12:59:26 CET 2013


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"
> 
> >     test = s.sub_is(1, -1, "bcd")    # yes! what I'm searching
> 
> You can use startswith() (or endswith) by providing the optional
> start and end arguments:
> 
> test = s.startswith("bcd", 1, -1)

That doesn't work, unfortunately:

py> s = "abcdZZZZZZZ"
py> s[1:-1] == "bcd"
False
py> s.startswith("bcd", 1, -1)
True


Oops.

You'd have to do both startswith() and endswith() tests, and even then 
it doesn't work:

py> s = "abcdZZZZZZZZabcde"
py> s[1:-1] == "bcd"
False
py> s.startswith("bcd", 1, -1) and s.endswith("bcd", 1, -1)
True


-- 
Steven



More information about the Tutor mailing list