value = "aabc"# Replace a substring with another.
result = value.replace("bc", "yz")
print(result)
# Replace the first occurrence with a substring.
result = value.replace("a", "x", 1)
print(result)aayz
xabc
Replace count. The third argument to replace() is optional. If we specify it, the replace method replaces that number of occurrences—this is a count argument.
Here We have a string that says "cat cat cat" and we replace all occurrences, 0 occurrences, and 1 and 2 occurrences.
before = "cat cat cat"
print(before)
# Replace all occurrences.
after = before.replace("cat", "bird")
print(after)
# Replace zero occurrences.# ... This makes no sense.
after = before.replace("cat", "bird", 0)
print(after)
# Replace 1 occurrence.
after = before.replace("cat", "bird", 1)
print(after)
# Replace first 2 occurrences.
after = before.replace("cat", "bird", 2)
print(after)cat cat cat
bird bird bird
cat cat cat
bird cat cat
bird bird cat
Regular expressions. Occasionally we need complex string replacement logic—for example, replacing substrings starting with certain letters. The re.sub method, part of the "re" module, works here.
Here We replace all substrings in a string starting with the 3-letter sequence "car" and replacing the entire match with the word "bird."
import re
# Replace all words starting with "car" with the string "bird".
s = "carrots trees cars"
v = re.sub(r"car\w*", "bird", s)
print(v)bird trees bird
A note. Replace() is needed to change a part of string to a new string. If the index of the match is known, we could use two slices and then construct a new string with concatenation.
Summary. With replace() we copy a string. The original is not changed. The copied string has the specified number of substrings replaced with a new substring (if found).
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 20, 2024 (new example).