python script to replace X number of string occurrences
top of page

python script to replace X number of string occurrences


You can use the replace command in python to replace a string for a set number of occurrences in which it appears in a set.

Designate a set using a letter and enter strings for the set between quotes.

>>> z = "InfoGov Identification Preservation Collection Processing Review Analysis Production Presentation"

Use the replace command, preceded by the designation for the set to indicate the terms you to find and replace:

>>> z = z.replace("Review","Litigation Support")

Output the result >>> print(z)

In order to replace only X number of occurrences of a string (starting from the beginning at the left) . . .

>>> x = "Volume Volume Set Set Folder Volume Folder File File Volume"

Modify the replace command by listing a number at the end of the values in parentheses: >>> x = x.replace("Volume","PRODUCTION",3) >>> print(x)

In this example only the first three instances of 'Volume' are replaced.


bottom of page