[SOLVED] Is there a way to select a certain letter in Python?

Issue

enter image description here

dna="AAGAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTCTTAGCGGGGCCACATCGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGTTACAGCGAGCATAC" 

So basically I was trying to select ONLY the letter "C"s in the dna variable, and simply replace it with the letter "G".

Is there a way/function I can have for this? Would be greatly appreciated if answered!

Solution

Use maketrans

Since you need:
C <-> G and A <-> T

Meaning C -> G and G -> C, etc.

Example

dna = "CGATCCGG" # dna sequence

# Create translation table
x = "CGAT"       # original letters
y = "GCTA"       # letters to map too
mytable = str.maketrans(x, y)  # Create translation table
                               # dna.maketrans(x, y) also works

# Apply table to dna string
translated = dna.translate(mytable)

# Show Original vs. translated
print(f"Original:\t{dna}\nTranslate:\t{translated}")
# Output:
Original:   CGATCCGG
Translate:  GCTAGGCC

Answered By – DarrylG

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *