0

I am trying to remove the vowels from a string: "This website is for losers LOL!" So when i try the following code it doesnt work and gives me the output which is same as the input:

str2="This website is for losers LOL!"
input1="aeiouAEIOU"
for char in input1:
    newstr4=str2.replace(char,"")
print(newstr4)

But if i try the following code it works:

str2="This website is for losers LOL!"
input1="aeiouAEIOU"
newstr4=str2
for char in input1:
    newstr4=newstr4.replace(char,"")
print(newstr4)

I just want to understand the difference between the two? Why does the first method not work when assign str2.replace to a new variable?

  • `newstr4=str2` **does not create a copy**. Anyway, `str` methods *always return a new string*, because `str` objects are immutable. So if you want to accumulate changes, you have to keep working on the strings being returned by the `.replace` method. Otherwise, it is always working on the same string – juanpa.arrivillaga May 07 '20 at 21:07
  • The reason is because strings are inmutable, see for example: https://stackoverflow.com/questions/9097994/arent-python-strings-immutable-then-why-does-a-b-work – braulio May 07 '20 at 21:10

3 Answers3

1
str1 = "This is string 1"
str2 = str1.replace("i", "")

The result is

>>> str1 == "This is string 1"
>>> str2 == "Ths s strng 1"

Notice how str1 has not changed. That means that you can assign str1.replace() to str2 as many times as you want, and str2 will only retain the last assignment, not the accumulation of all the assignments. By contrast, using str1 = str1.replace(), you are constantly changing str1, accumulating changes as they happen.

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
0

The function replace doesn't change the value of str2. It only returns a copy of it with the changes you wanted. so in the second iteration (no "a" in your string) newstr4 will be equal to This wbsite is for losrs LOL!, but str2 will still be This website is for losers LOL!, so in the next iteration all the e's will be back in newstr4 and all i's will be gone, and so on.

if you want the changes to pile-up you can do str2 = str2.repalce(char, "")

Gal
  • 504
  • 4
  • 11
0

Look when you use a new variable and using it in for loop like [ newstr4 ] every time you just get str2 and changing it into something new in newstr4 but the next time the loop will getting the original str2 again and will change base on another char. So maybe you asking your self why we dont have any changes in the last time of loop because you do not have any capital u [U] in the str2

you can change it to this to but the original str2 will change : str2="This website is for losers LOL!" input1="aeiouAEIOU" for char in input1: str2=str2.replace(char,"") print(str2)

Aram.rt
  • 61
  • 1
  • 3