Showing posts with label python_sub. Show all posts
Showing posts with label python_sub. Show all posts

Jan 25, 2019

Python re subn

import re

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

#subn - returns a tuple with no of substitutions made

print re.subn('python', 'PYTHON', text, count=0, flags=0) #replaces all
#('PYTHON is good, PYTHON is better, PYTHON is best', 3)

print re.subn('python', 'PYTHON', text, count=1, flags=0) #replaces first
#('PYTHON is good, python is better, python is best', 1)

print re.subn('python', 'PYTHON', text, count=2, flags=0) #replaces first & second
#('PYTHON is good, PYTHON is better, python is best', 2)

print re.subn('python', 'PYTHON', text, count=3, flags=0) #replaces first, second, third
#('PYTHON is good, PYTHON is better, PYTHON is best', 3)

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