If the string is relatively small, I would use str.split('\n') to split it into a list of strings. Then change the desired line and concatenate the list:
l = mystr.split('\n') l[2] += ' extra text' mystr = '\n'.join(l)
In addition, if you can uniquely identify how the string you want to add to the ends, you can use replace . For example, if the line ends with x , you can do
mystr.replace('x\n', 'x extra extra stuff\n')
source share