[Tutor] Slicing index

Mats Wichmann mats at wichmann.us
Sun Oct 18 11:55:26 EDT 2020


On 10/18/20 6:57 AM, Carlene Wong via Tutor wrote:
> Hello, I’m new but I’m getting trouble with slicing an index into another.
> Eg. Def mysentence (sentence, old, new)
>  If old in sentence[-4:]:
> n= sentence.index(old)
> newsent=Sentence [:n]+new
> return newsent
> return mysentence
> print(mysentence(“Hello there, it’s raining cats and cats”, “ cats”, “ dogs“)
> 
> It keeps printing
> Hello there, it’s raining dogs

If you've transcribed that correctly, which one suspects you haven't,
that's not what you should get.  (in future, please paste directly from
a code editor - I see in the print statement what looks like
Microsoft-style smart quotes, which are not a valid Python string
delimiter, plus the indentation is all wrong to be syntactically correct)

In your function, you try to match the passed-in string, which as
written is five characters " cats" (including a leading space) to a
slice of the last four characters of sentence, which will never match.

On to your actual question: you're trying to first check if the string
to be replaced appears at the end of the sentence, but then when you
call the index method, you'll get the index of the *first* match (use ,
and you slice that off and add the replacement string, so the outcome is
as one would expect in this case - the selected slice is "Hello there,
it's raining" and you add to that " dogs".  Use rindex() if you want to
match from the right, aka the *last* match.



More information about the Tutor mailing list