I have many pairs of lines and one large line (this is the contents of the file). I need to replace each occurrence of the first member in each pair with the corresponding second.
For example, having the pairs ("AA", "BB") and ("qq", "rt"), I need to replace each occurrence of AA with BB and qq with rt .
Lines in pairs are unique, so the order of replacement does not matter in the final result.
My python code is the most naive - I use the string.replace method sequentially until all the pairs are exhausted:
>>> s="frsfsdAAsdfvsdfvqqdsff" >>> pairs=[('AA', 'BB'), ('qq', 'rt')] >>> for p in pairs: ... s=s.replace(p[0], p[1]) ... >>> s 'frsfsdBBsdfvsdfvrtdsff' >>>
I believe this is a bad solution for large strings. Can anyone suggest a more efficient one?
The question is how to do this in Python.
Thanks.
source share