I have a text file that has a bunch of data in it. At certain instances of this text file, I am trying to replace the follow letters in it: A->G, C->T, etc. Basically, I know I need to read the file. Search through the lines of the file. Find the occurrences of these characters and then replace. Basically –> ACTG should be come GTCA.
My code so far is as follows:
f = open("actg.txt", "r")
table = str.maketrans("actgACTG", "gtcagtca")
print(f.read().translate(str.maketrans('ACTGactg','gtcagtca')))
print(table)
This output here is working properly. However, it’s changing ALL instances of such letters in the entire file.
What if I only want the characters to change like this when they’re in this particular sequence? Otherwise, as it is, it changes every ‘a’ and every ‘g’ in the entire file. I would like to keep normal sentences intact and only have this change made when this particular sort of sequence is present.
You can use
str.translatein combination withstring.maketrans(Python 2.x) orstr.maketrans(Python 3.x):Python 2.x:
Python 3.x:
translaterequires a 256 character mapping table. This is whatstring.maketranscreates, mapping each character to itself, except for characters in the first argument string which are mapped to the corresponding character in the second argument string.