Skip to content
Advertisement

how does replace function work in python 3.x

I am new to Python, I read in a book that strings are immutable. Then how does replace() function work in Python? Does it slice up to the part where it finds the text that we want to replace and add the text with new string and then add the remaining text which is after the text we want to replace.

Advertisement

Answer

The documentation for str.replace says:

Return a copy of the string with all occurrences of substring old replaced by new.

From here:

There is also no mutable string type, but str.join() or io.StringIO can be used to efficiently construct strings from multiple fragments.

However, it looks like, at least in the standard implementation, replace is implemented in native code.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement