[Tutor] Slicing index

dn PyTutor at DancesWithMice.info
Sun Oct 18 15:51:38 EDT 2020


On 19/10/2020 01: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)
>   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


(adding to other replies) Some have suggested (IMHO: better) approaches 
other than slicing.

Assuming your assignment is to learn how to use "slicing", don't change 
methods part-way (by using string.index() )!

0 start with sentence
1 grab the last four characters into a new string:
	in sentence[ -4: ]
2 similarly, use the same structure if the sentence is to be changed:
	sentence[ :-4 ] + new


Yes, please copy-paste from the Python interpreter/REPL (or editor/IDE) 
the source code, the full error and "stack trace", plus relevant i/p and 
o/p - also, the text of the assignment/problem. (so, (see "Assuming" 
above) that we can help you learn the particular technique that the 
course is covering today!)



Advanced coding technique:
- notice how the "-4" appears twice (in the suggested solution, above)
- if we wanted to re-use the code to handle tigers, we now need to 
examine more than the last four characters!
(did I say "advanced"? Handling cats is tricky, but handling tigers is 
dangerous!)
- how many times would we have to make changes to the code?
- what are the chances we would 'forget' and only make one change?
So,
it is a good idea to 'parameterise' such values, eg
	suffix_length = -4
	...
	in sentence[ suffix_length: ]
	...
	sentence[ :suffix_length ] + new
Now,
we would only have to change the "control" once, to handle cats of any 
size and length of claws!
-- 
Regards =dn


More information about the Tutor mailing list