C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: The third argument is optional. It is a count. It indicates the maximum number of instances to replace.
Tip: Replace only handles substrings, not characters. If you need to replace many single characters, please consider the translate method.
TranslatePython program that uses replace
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)
Output
aayz
xabc
Here: We have a string that says "cat cat cat" and we replace all occurrences, 0 occurrences, and 1 and 2 occurrences.
Python program that uses replace, count argument
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)
Output
cat cat cat
bird bird bird
cat cat cat
bird cat cat
bird bird cat