Reputation: 13
I'm new to coding and python is my first language. I'm trying to make a function which removes all the special characters, but I can't seem to find the problem whenever I use this:
def Remover(sentence):
special_chars = (',', '.', '!',';', ':', '\"','','|')
for char in special_chars:
for words in sentence:
if words == char:
replaced_sentence = sentence.replace(words, "")
print replaced_sentence
When I enter
hi,
I get this
hi
Which is what I want, but when I enter hi, hi,
I get this:
hi hi
hi hi
Why? I should get hi hi
but why 4 times?
OUTPUT
Upvotes: 0
Views: 94
Reputation: 2682
The problem with your code is that you print your new sentence
inside of the for
loop. This means, for every time you encounter a special character, you print
the new sentence.
You should wait until you have finished looping to print
(so it only happens once).
However, you are also misusing the replace
function. I would suggest you change your code to something like this instead:
def Remover(sentence):
special_chars = (',', '.', '!',';', ':', '\"','','|')
for special_char in special_chars:
sentence = sentence.replace(special_char, '')
print(sentence)
This would be the proper way to use the replace
function, instead of looping over your string and then doing replace
. The replace
function replaces all instances of a character in a string, so you only need to use it once.
Upvotes: 4
Reputation: 12181
As others have indicated, you're currently printing every time you do a replace (not just when you're done editing the string). You'll print exactly as many times as you replace; for example, hi, hi,
has 2 replace operations. hi,,,, hi
has 4. Thus, you'll replace 2 times followed by 4 times. (I'd encourage you to try that at this point to convince yourself that that's the case).
Try this:
def Remover(sentence):
special_chars = (',', '.', '!',';', ':', '\"','','|')
for char in special_chars:
for words in sentence:
if words == char:
replaced_sentence = sentence.replace(words, "")
print replaced_sentence
Simply print at the end once you're editing the string (instead of editing every time).
Upvotes: 1
Reputation: 780688
You're printing the replacement every time words == char
is true. So if there are two ,
in the sentence, you'll print the replacement twice.
You don't need to loop over the sentence. sentence.replace()
will replace all the occurrences of the character, so you only need to call it once for each character you want to replace.
You also need to assign the replacement back to the sentence
variable, so that you'll get all the replacements in one place. Otherwise, each time you're starting from the same original string, replacing a different character, and the final result will just be from the last set of replacements.
def Remover(sentence):
special_chars = (',', '.', '!',';', ':', '\"','','|')
for char in special_chars:
sentence = sentence.replace(char, "")
print sentence
Upvotes: 1