The replace method in Python replaces a phrase in a string with another phrase. By default, all occurrences are replaced. How can you tell Python just to replace the first occurrence?

Replace only the first phrase occurrence in a Python string.

You have seen the replace function in Python. It takes two arguments: oldphrase and newphrase:

a = "a/b/c/a/b/c"
print(a.replace("a/", ""))

The method operates on string a and replaces all occurrences of a/ with empty string "".



Only replace first occurrence

To replace the first occurrence only, add a third argument (count) with value 1.

a = "a/b/c/a/b/c"
print(a.replace("a/", "", 1))



As you see, the first occurrence of a/ has been removed. The second occurrence is still in the result.

Written by Loek van den Ouweland on 2020-08-24.
Questions regarding this artice? You can send them to the address below.