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 139 times
-1
bad_coder
- 8,684
- 19
- 37
- 59
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
- 7,457
- 5
- 15
- 37
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
- 670
- 5
- 18
-
Try not to shadow the builtin str object . – 12944qwerty May 16 '21 at 15:07