0

I do the following for replacing.

import fileinput
for line in fileinput.FileInput("input.txt",inplace=1):
     line = line.replace("A","A'")
     print line,

But I want to do it many replaces.

Replace A with A' , B with BB, C with CX, D with KK, etc.

I can of course do this by repeating the above code many times.

But I guess that will consume a lot of time especially when input.txt is large.

How can I do this elegantly?

Emphasis added

My input is not just a str ABCD.

I need to use input.txt as input and I want to replace every occurrences of A in input.txt to A', every occurrences in input.txt of B to BB, every occurrences of C in input.txt to CX, every occurrences of D in input.txt to KK.

2 Answers 2

4

Use a mapping dictionary:

>>> map_dict = {'A':"A'", 'B':'BB', 'C':'CX', 'D':'KK'}
>>> strs = 'ABCDEF'
>>> ''.join(map_dict.get(c,c) for c in strs)
"A'BBCXKKEF"

In Python3 use str.translate instead of str.join:

>>> map_dict = {ord('A'):"A'", ord('B'):'BB', ord('C'):'CX', ord('D'):'KK'}
>>> strs = 'ABCDEF'
>>> strs.translate(map_dict)
"A'BBCXKKEF"
Sign up to request clarification or add additional context in comments.

7 Comments

Is it using strs as input? I need to use input.txt as input and I want to replace every occurrences of A in input.txt to A', every occurrences in input.txt of B to BB, every occurrences of C in input.txt to CX, every occurrences of D in input.txt to KK.
@user2604484 Then simply use the text read from input.txt instead of strs.
Hmm I am sorry but I just started to learn python, could you edit the codes in the answer to write the full changes needed including "reading from input.txt"?
@user2604484 Have you tried: line = ''.join(map_dict.get(c,c) for c in line) ?
Thank you! However I got one question. You wrote {'A':"A'", 'B':'BB', 'C':'CX', 'D':'KK'} Here, what replaces A is wrapped by " and ", but what replaces B, C, D are wrapped by ' and '. Why? Should the first one be always " instead of ' ?
|
1

Using regular expression:

>>> import re
>>>
>>> replace_map = {
...   'A': "A'",
...   'B': 'BB',
...   'C': 'CX',
...   'D': 'KK',
...   'EFG': '.',
... }
>>> pattern = '|'.join(map(re.escape, replace_map))
>>> re.sub(pattern, lambda m: replace_map[m.group()], 'ABCDEFG')
"A'BBCXKK."

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.