user2931871 user2931871 - 6 months ago 13
Python Question

Python - manually removing a specific letter from a string

I'm aware of the

string.replace("x", "y")
method, but I'm trying to manually remove a character from a string to help me better understand Python and programming in general. The method I currently have is detailed below, but I can't understand why for "Dee" and removing "e" it will return "De", but for "John Do" and removing "o" it will return "Jhn D". Thus, it is removing two letters, but only one letter in the first.

Any help would be much appreciated.

def remove_letter(): # Remove a selected letter from a string
base_string = str(raw_input("Enter some text: "))
letter = str(raw_input("Enter the letter to remove: ")) # takes any string size
letter = letter[0] # ensures just one character is used
length = len(base_string)
location = 0

while location < length:
if base_string[location] == letter:
base_string = base_string[:location] + base_string[location+1::]
# concatenate string using slices
length -= 1
location += 1

print("Result %s" % base_string)


The problem oyu have is that you change the size of the string you want to remove the letter from, while removing the letter :
When you remove the first 'e' in Dee, you have location = 1, corresponding to the first 'e, but is now that of the second 'e'. After removing the e, at the end of the current loop, you have location = 2, and length = 2, so stop looping.

How to resolve the problem : Increase the location ONLY when you do not find the letter :

    location += 1

This will prevent your loop from not checking the letter right after a removed letter.

If you need any more explanation, just ask.