How do I delete a substring from a string without using .replace()?
<p>For my CS class we try to focus on creating and using algorithms instead of just using built in methods. For this program I have to remove a substring from a string (if the substring is in the string), but I can't use .replace(). I can't figure out how to do this without 'hardcoding' and not coming up with an algorithm that works for all cases. I've tried just adding the characters into a new list unless they are in the substring, but this doesn't work if there's a character in the substring but not part of the substring within the string. Can anyone point me in a direction that can help me solve this?</p>

<p>The string I'm having trouble with is 'eph' in 'catelephant' and 'eph' in 'cephatelephant'. </p>

<p>I've tried iterating using something like this:</p>

<pre><code>string2 = ""
if substring in string1:
    for i in string1:
       if i != substring1
          string2 += i
</code></pre>

<p>But this is obviously problematic as it doesn't account for multiples of the same character in the substring but are not within the substring in the string. i.e. the first e in catelephant would be removed. </p>

<p>edit: i can only use the len() or append functions</p>

<p>You can do that:</p>

<pre><code>myString = myString[0:myString.index(mySubstring)] + myString[myString.index(mySubstring)+len(mySubstring):]
</code></pre>

<p>But of course it will replace just the first occurrence. So if mySubstring is <em>eph</em> and myString is <em>cephatelephant</em> and you would like to remove the two substrings, you would have to call the code above twice. For example (I'm using ipython here):</p>

<pre><code>In [14]: mySubstring = 'eph'

In [15]: myString = 'cephatelephant'

In [16]: myString = myString[0:myString.index(mySubstring)] + myString[myString.index(mySubstring)+len(mySubstring):]

In [17]: print myString
catelephant

In [18]: myString = myString[0:myString.index(mySubstring)] + myString[myString.index(mySubstring)+len(mySubstring):]

In [19]: print myString
catelant
</code></pre>

python python-2.7