0

Why does the code in python work differently in #1 and #2? #1 works when I make a new b string(like in #1-1 instead of #1-2), but #2 works without making a new list.

#1
#1-1
a="a:b:c:d"
b=a.replace(":","%")

print(b)
#1-2
a="a:b:c:d"
a.replace(":","%")

print(a)




#2
a=[1,3,2]
a.sort()
print(a)
jangsk109
  • 1
  • 1
  • In #2 the replacement isn't "sticking." Strings are immutable in Python, and you need to make an assignment on the LHS of the replacement in order to persist the results of the replacement. – Tim Biegeleisen Oct 31 '20 at 13:29
  • 1
    `a = a.replace(":","%")` replace and assign the result to `a`; when `a.replace(":","%")` is to replace and *throw away* the result – Dmitry Bychenko Oct 31 '20 at 13:35
  • 1
    Strings are immutable in Python; therefor, any methods that modify them return a NEW string. If you do not capture the return, it is lost. – dawg Oct 31 '20 at 13:57

1 Answers1

0

The replace method returns a copy of the string with the changes, the input is not changed. So in #1 store modified string in a new value b and a does not change. In #2 you ignore the modified result. Just calling the function does not modify the string.

jjj
  • 575
  • 1
  • 3
  • 16
  • Thank you for your kind answer. Then why does the code in python work differently in #1 and #2? #1 works when I make a new b string(like in #1-1 instead of #1-2), but #2 works without making a new list. #1 #1-1 a="a:b:c:d" b=a.replace(":","%") print(b) #1-2 a="a:b:c:d" a.replace(":","%") print(a) #2 a=[1,3,2] a.sort() print(a) – jangsk109 Oct 31 '20 at 13:42