Jan 25, 2019

Python substitute nth occurance

import re

##Substitue 3rd occurrence of 'python' with 'PYTHON'

nth_occurance = 3
text = 'python is good, python is better, python is best';

count = text.count('python')
if count <= 1:
print re.sub('python', r'PYTHON', text)
else:
print re.sub('^((.*?python.*?){' + str(nth_occurance-1) + '})python', r'\1PYTHON', text)


Output:
python is good, python is better, PYTHON is best

No comments:

Post a Comment