If you have text, you can run re.sub () directly on the entire text as follows:
import re ss = '''that a line another line a line to $$test$$ 123456 here $$test$$ again closing line''' print(ss,'\n') key = {0:'test', 1:'replace'} regx = re.compile('\$\${[0]}\$\$'.format(key)) print( regx.sub(key[1],ss) )
.
If you are reading a file, you should be interested in reading the entire file and placing it in the ss object before running re.sub () on it instead of reading and replacing the line after line
.
And if you have a list of strings, you should handle the following:
import re key = {0:'test', 1:'replace'} regx = re.compile('\$\${[0]}\$\$'.format(key)) lines = ["that a line", 'another line', 'a line to $$test$$', '123456', 'here $$test$$ again', 'closing line'] for i,line in enumerate(lines): lines[i] = regx.sub(key[1],line)
Otherwise, the line containing "$$ test $$" will not be changed:
import re key = {0:'test', 1:'replace'} regx = re.compile('\$\${[0]}\$\$'.format(key)) lines = ["that a line", 'another line', 'a line to $$test$$', '123456', 'here $$test$$ again', 'closing line'] for line in lines: line = regx.sub(key[1],line) print (lines)
result
["that a line", 'another line', 'a line to $$test$$', '123456', 'here $$test$$ again', 'closing line']