0

Consider a text file and 2 lists. In list_A there are some letters and in list_B some other letters. I want an algorithm to find the letters in the text which exist in list_A, and replaces them with letters with the same index from list_B. It finds and replaces them, but, each time it replaces it the previous result disappears.

I mean at last, I have the result of the last replacement in the print. How can I solve this problem? I mean I want a print in which all the letters are replaced, not just the last one. what could be the problem with this loop:

for i in text:
     if i in list_A:
         p=text.replace(i, list_B[list_A.index(i)])
print(p)
2
  • 2
    Consider maketrans + translate. Commented Mar 14, 2016 at 9:29
  • how about p+=text.replace...? Commented Mar 14, 2016 at 9:29

2 Answers 2

2

With this line:

p=text.replace(i, list_B[list_A.index(i)])

Each time through the loop you're taking text and assigning a new version of it to p, but you're never updating text to contain the new copy (Which you probably shouldn't do, as you're iterating over it).

I'd start by making p a copy of text outside the loop, and inside, doing p = p.replace(...

Bear in mind that with the method you've chosen, you also have to worry about multiple replacements and the order in which you're checking. For example, if you are replacing all a with b, and also wanting to replace all b with c, then using your method if you start with aaaa you will end up with cccc (because it replaces them all with b, then checks for b...) , when you might have only wanted to replace the a if it was in the original string. If you're worried about that, I'd look at maketrans and translate as mentioned by bereal in a comment.

Sign up to request clarification or add additional context in comments.

3 Comments

I agree with your comment above about maketrans and translate, but I wanted to make sure the answer would explain the error in the code the OP gave so that it would help with future errors like that. We can do optimisation afterwards :)
Sorry I misread your answer, so my performance-related comment is irrelevant.
I generalised your comment to be one about optimisation, it's ok :)
0

This should work.

 temp = text
 for i in temp:
     if i in list_A:
         temp=temp.replace(i, list_B[list_A.index(i)])

print "Original:",text
print "Modified: ",temp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.