[Tutor] string codes

Alan Gauld alan.gauld at btinternet.com
Tue Nov 26 15:41:44 CET 2013


On 26/11/13 11:59, Steven D'Aprano wrote:

>> 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:

Since the OP suggested startswith/endswith I assumed that's what he 
wanted... His example:

     s = "abcde"
     test = s[1, -1] == "bcd"    # no!, builds a substring
     test = s.sub_is(1, -1, "bcd")    # yes! what I'm searching

tests the substring 'bcde' and apparently was expected to
return True for 'bcd'... hence the suggestion to use
startswith

If he wants to test for equality of a substring  then
provided the start/end are set correctly startwith will
still work, but you need to ensure that end is exactly 
(start+len(subst)). ie

test = s.startswith('bcd', 1, 1+len('bcd') )

And that's a bit error prone so I'd still opt for slicing.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list