This advertisement helps me to keep writing articles on this website

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: 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 "".

Output:

b/c/b/c

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))

Output:

b/c/a/b/c

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 August 24, 2020. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.