[Tutor] Slicing index

Mark Lawrence breamoreboy at gmail.com
Sun Oct 18 12:22:05 EDT 2020


On 18/10/2020 13:57, 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)

This will fail with a syntax error as 'Def' is wrong.

>   If old in sentence[-4:]:

Fix the 'Def' and this looks for 'old' starting 4 characters from the 
end of 'v'.

> n= sentence.index(old)

Fix the indentation and this finds the index of 'old'

> newsent=Sentence [:n]+new

This will fail as 'Sentence' does not exist.  Fix that and I think 
you'll get what you want, I'm feeling too lazy to try it for myself.

> return newsent

Fix all the above and you'll get here eventually.

> return mysentence

I'll assume that you mean to return the original 'sentence' here if you 
don't take the 'if' path.

> print(mysentence(“Hello there, it’s raining cats and cats”, “ cats”, “ dogs“)
> 
> It keeps printing
> Hello there, it’s raining dogs

No it doesn't, see all the above problems.  Having said that for this 
sort of problem I'd probably look at string methods 
https://docs.python.org/3/library/stdtypes.html#string-methods rather 
than slicing.

> 
> Your help
> 
> Sent from my iPhone
> 

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list