[Tutor] string codes
spir
denis.spir at gmail.com
Wed Nov 27 22:20:03 CET 2013
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"
>>
>>> 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
Hum, I don't understand the reasoning, here.
* First, why use the end-index param? (Here in this case, or in any other)? It
contradicts the idea of starting with in my view, but also is useless for
sub-equality checking.
* 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'?
All in all, startswith plus start-index only seems to work fine, I guess. What
is wrong? string.find also works (someone suggested it on the python-ideas
mailing list) but requires both start- and end- indexes. Also, startswith
returns true/false, which is more adequate conceptually for a checking instruction.
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.
>>> s = "abcde"
>>> s.startswith("bcd", 1)
True
>>> s.find("bcd", 1, 4)
1
>>> s = "abcdefghi"
>>> s.startswith("bcd", 1)
True
>>> s.startswith("bcd", 2)
False
>>> s = "fghiabcde"
>>> s.startswith("bcd", 5)
True
>>> s.startswith("bcd", 1)
False
>>> s.startswith("bcd", 9)
False
I really want to know if I'm missing an obvious logical point, here; else, I
will stupidly use startswith, which seems to do the job, and this w/o unduly
creating unneeded string objects.
Denis
More information about the Tutor
mailing list