KL777
KL777

Reputation: 43

Is there a way to select a certain letter in Python?

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!

Upvotes: 1

Views: 741

Answers (4)

Asdoost
Asdoost

Reputation: 394

If you want to replace Cs with Gs, use this:

dna.replace('C', 'G')

Upvotes: 2

DarrylG
DarrylG

Reputation: 17166

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

Upvotes: 7

imbes
imbes

Reputation: 63

for general replacement, you can use str.replace(target, replacement) but the issue in the context of the problem is that if you string replace all the C's with G's, you don't know what was originally a G to replace to a C to get the compliment.

It would be better to convert the strand into a list, then replace values one by 1 with case blocks or if/else blocks:

def dna_compliment(strand):
  listStrand = list(strand)
  for i in range(len(listStrand)):
     if listStrand[i] == 'C':
        listStrand[i] = 'G'
     elif ...
     ...
  return ''.join(listStrand)

Upvotes: -1

BrokenBenchmark
BrokenBenchmark

Reputation: 19252

You can use .replace():

dna=("AAGAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTCT"
"TAGCGGGGCCACATCGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGTTACAGCGAGCATAC")

print(dna.replace("C", "G"))

Upvotes: 2

Related Questions