How do I replace a string in Python?

To replace a string in Python, you can use the built-in string.replace() method. This method returns a copy of the string in which the old substring has been replaced by the new substring and does not change the original (strings in Python are immutable). If the substring is not found, a copy of the original string is returned. Optionally, you can limit the number of replacements by specifying the "count" argument. In this case, only the first "count" occurrences will be replaced. If the "count" argument is not specified, then all occurrences of the substring will be replaced. In this Python String Replace Example, we use the string.replace() method to change all occurrences of a substring in the string. Click Execute to run the Python String Replace Example online and see the result
Loading...