Does .replace()
always need to be declared inside a print()
statement or can you use it to change a string permanently? If so, how?
Asked
Active
Viewed 792 times
-1

bad_coder
- 11,289
- 20
- 44
- 72
2 Answers
1
Since strings are "immutable" objects, you can't mutate it at all. It's true for all of it's methods.
.replace
is also create a new string object for you.
s1 = 'hello'
s2 = s1.replace('e', '3')
print(s1, id(s1))
print(s2, id(s2))

S.B
- 13,077
- 10
- 22
- 49
1
You don't need to use .replace()
always inside of print()
Like the below example, you can change the str
with .replace()
and then print changed str
myStr = "I love programming"
myStr = myStr.replace("programming", "chicken Nugget")
print(myStr)

Seungjun
- 874
- 9
- 21