Python String replace(): Replace Characters in a String
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
The str.replace() method returns a new string with occurrences of a substring replaced by another substring. Its basic syntax is original.replace(old, new, count), where old is the substring to find, new is the replacement text, and the optional count limits how many replacements are made from the left. If count is omitted or -1, all occurrences are replaced. The method accepts strings as arguments and returns a string; the original string remains unchanged because Python strings are immutable.
Inputs can be single characters, longer substrings, or an empty string. Outputs include the transformed string. To remove characters, replace them with "". You can also chain calls to perform multiple replacements, as in text.replace("l", "L").replace("o", "0"). Note that replace() is case-sensitive and does not support regular expressions; use re.sub() for patterns.
Time complexity is generally O(n), where n is the length of the original string, since Python scans and builds a new string. Space complexity is O(n) for the returned string. The optional count can reduce work when only a few leading matches are needed. Use replace() for simple, readable character or substring substitutions. It is commonly used in data cleaning to normalize text, swap delimiters, or format user input. Always test edge cases such as missing substrings, which leave the string unchanged.