Can someone explain me why does the first function get trough and not the second one. I can't figure out why I cannot assign a new var to the parameter 'string_' I tried to search online but I can't find a name to that problem therefore I am running in circles.
First
def disemvowel(string_):
for i in "aeiouAEIOU":
string_ = string_.replace(i, "")
return string_
Second
def disemvowel(string_):
for i in "aeiouAEIOU":
string = string_.replace(i, "")
return string
CodePudding user response:
Sometimes a small print
is better that an long explanation:
Option 1 (cumulative modifications):
def disemvowel(string_):
for i in "aeiouAEIOU":
string_ = string_.replace(i, "")
print(i, string_)
disemvowel('aeizAEIZ')
a eizAEIZ
e izAEIZ
i zAEIZ
o zAEIZ
u zAEIZ
A zEIZ
E zIZ
I zZ
O zZ
U zZ
Option 2 (successive modifications):
def disemvowel(string_):
for i in "aeiouAEIOU":
string = string_.replace(i, "")
print(i, string)
disemvowel('aeizAEIZ')
a eizAEIZ
e aizAEIZ
i aezAEIZ
o aeizAEIZ
u aeizAEIZ
A aeizEIZ
E aeizAIZ
I aeizAEZ
O aeizAEIZ
U aeizAEIZ
CodePudding user response:
The second function uses the unmodified caller argument for each replace
, assigning to a different variable. As such, only the final replace
(for 'U'
) has any effect. Reusing the argument (as you did in the first function) means you accumulate the changes rather than discarding each one in favor of the latest.
As a side-note, the work you're doing could be done in a single operation instead of requiring 10 separate replace
calls:
# Done outside the function once so it can be reused without the expense of
# rebuilding it
# Creates a dict mapping all vowels to None, for use with str.translate,
# which interprets mapping to None as "delete this character"
_kill_vowels_table = str.maketrans('', '', 'aeiouAEIOU')
def disemvowel(string):
return string.translate(_kill_vowels_table)
CodePudding user response:
It seems not working in the second code piece because you assigned the result of replace
method to a different variable each time. If you type any input that finishes with U
character you will see that it will be replaced with empty string.
def disemvowel(muz):
for i in "aeiouAEIOU":
elma = muz.replace(i, "")
return elma
print (disemvowel('ovyeahbananaU'))
it returns ovyeahbanana
CodePudding user response:
In 2nd code. As string_
is unmodified on next for-loop run it won't remove the elements it removed before. So it will continue until last chr ("U" in your case). So it will only replace last chr with ""
.
def disemvowel_notworking(string_):
for i in "aeiouAEIOU":
string = string_.replace(i, "")
return string
print(disemvowel_notworking("HELLO WORLD Ucheck"))
output
HELLO WORLD check