-1

Does .replace() always need to be declared inside a print() statement or can you use it to change a string permanently? If so, how?

0

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.