-2

In the following example, I would have expected an error saying that string assignment is not possible because strings are immutable. Instead, the loop returns the original string.

a = "AECD"

for i in a:
    if i == "E":
        a.replace(i, "B")
        print(a)

Is replace not essentially trying to do the same thing as a[1] = "B"? Does this have to do with creating a new object with assignment versus modifying an existing one with replace?

username
  • 75
  • 5

3 Answers3

0

Try this:

a = "AECD"

for i in a:
    if i == "E":
        b = a.replace(i, "B")
        print (b)
        print(a)
Danielle M.
  • 3,607
  • 1
  • 14
  • 31
0
a.replace(i, "B")

does not change the original string a. Instead, it returns the string which results from replacing i in a. In your loop, you are merely evaluating an expression and dropping it on the floor.

You could do it this way:

a = "AECD"

for i in a:
    if i == "E":
        a = a.replace(i, "B")
        print(a)

In this version, you take the string with the replacement, and you assign that value to the variable a, which gives you the effect you were expecting.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
0

Since you're not doing a string assignment, this is not an error. A new string is being created and is returned by the str.replace() method. You are throwing it away by not assigning it to anything, however.

kindall
  • 178,883
  • 35
  • 278
  • 309