This is a great topic for a beginner. Your question left a good latitude for interpretation, which makes it a little difficult to offer laser-precision support, but we all had to start out as newcomers once upon a time so here's a scattershot answer.
You can find out whether your string is a candidate for this treatment by determining whether the required string occurs at the beginning.
>>> "tunasandwich".startswith("tuna")
True
If this is the case then you know you want to remove the first four characters or, to put it another way, you want the string starting at character number four (remember, elements of any sequence are counted from zero, so number four is the fifth element). You can do this with an "open-ended slice":
>>> "tunasandwich"[4:]
'sandwich'
The [4:]
says create another string from character number four right through to the end of the string (so you don't even need to know how long the string is). More generally, it would be useful to write a piece of code that worked for any two strings. Let's suppose we wrote:
>>> target = "tuna"
>>> subject = "tunasandwich"
>>> # This code should work for any two strings (perhaps...)
...
>>> if subject.startswith(target):
... subject = subject[len(target):]
...
>>> subject
'sandwich'
Try the same thing with different values for target
and subject
. You should find that only when the subject string actually does start with the target string, the subject string is replaced with the substring that follows the target. Instead of using a number like four as the start of the substring I have used the computed length of the target, so the code adapts to any target string. Checking that the target occurs at the start of the subject stops us chopping up strings that aren't eligible fpor the treatment.
Of course eventually you will get tired enough of all the typing to want to learn about functions, but that can wait for another day.