Question

Okay back with another one. I have:

var1 = "tuna"
var2 = "tunasandwich"

I want:

var3 = "sandwich"

I know my questions are very elementary but I am asking them simple and looking for simple answers as I am very new to programming. A lot of the questions asked here are above my head so if others who are beginners like me search they will find my simple beginner questions and answers.

thanks

Était-ce utile?

La solution

Use the replace function. So say:

var1 = "tuna"
var2 = "tunasandwich"
var3 = var2.replace(var1, "")

The value of var3 will then be sandwich.

What we're doing is replacing all occurrences of var1 with the empty string "" that occur in var2, and setting that equal to var3.

This will replace all instances in the string.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top