REPLACE()

This method is used to create a new string in which all occurrences of a specified substring are replaced with another substring. Its basic syntax is string.replace(old, new[, count]), where old is the substring to be replaced, new is the replacement string, and count is an optional argument specifying the maximum number of replacements to perform. The method is case-sensitive, so substrings must match exactly in case to be replaced. It does not modify the original string, as strings in Python are immutable, but returns a new string with the replacements applied. For example, "hello world".replace("world", "Python") returns "hello Python". For case-insensitive replacements, the re.sub() function from the re module with the flags=re.IGNORECASE option can be used. This method is commonly used for text processing tasks such as formatting, data cleaning, and content modification.

SINGLE CHARACTER

myString = "Chaf"
myString_new = myString.replace('a', 'e')  
print(myString_new)      #This string has the correct values

 * The replace() method is case-sensitived and replaces all occurrences 
   of the provided character.
#SPECIFIC OCCURRENCE REPLACEMENT ONLY
myString = "Chaaf"
myString_new = myString.replace('a', 'e', 1)  # Replace only the first 'a'
print(myString_new)  # Output: "Cheaf"

 * The count argument in replace() applies from left to right, starting at the 
   beginning of the string.
    - used it to limit the replacement

SUBSTRING

myString = "Hello World"
newString = myString.replace("World", "Python");
print(newString);

 * OUTPUT
    Hello Python

Last updated