Reputation: 79
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)
Upvotes: 3
Views: 353
Reputation: 103
Considering what khelwood and HolyDanna said, this might be a viable approach:
def removeletter(string, letter):
out = ''
for i in string:
if not i == letter:
out += i
return out
altered_string = removeletter(string, letter)
EDIT - You could also easily extend this to work as the str.replace()
method does, but only for single characters:
def stringreplace(string, letter, replacement):
out = ''
for i in string:
if i == letter:
out += replacement
else:
out += i
return out
altered_string = stringreplace(string, letter, replacement)
Upvotes: 3
Reputation: 629
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 :
else:
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.
Upvotes: 3