Replace only the first phrase occurrence in a Python string
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?
You have seen the replace function in Python. It takes two arguments:
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
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.