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)

No comments:

Post a Comment