Python Forum
Replacing characters in a string with a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Replacing characters in a string with a list (/thread-23436.html)



Replacing characters in a string with a list - cjms981 - Dec-30-2019

I am trying to take a string of DNA bases and partition the string into codons followed by replacing each codon one by one with a list of codons while keeping the rest of the sequence untouched.

For instance,

If a DNA sequence is ATG GCC

and the possible codons for replacement are TCC GGG

the possible combinations would be TCC GCC, GGG GCC, ATG TCC and ATG GGG.

So far i've written some code to Splice the DNA sequence into codons

from itertools import zip_longest

def grouper(iterable, n, fillvalue='x'):

    args = [iter(iterable)] * n


    ans = list(zip_longest(fillvalue=fillvalue, *args))

    t = len(ans)
    for i in range(t):
        ans[i] = "".join(ans[i])
    return " ".join(ans)

s = "ccggcgaacccgggcaccaccgccacgtacctc"
k = 3

Splice = grouper(s, k)
print(Splice)
I'm not sure if I can now use Itertools to try to replace each codon with my list or if I need to take an alternative approach?


RE: Replacing characters in a string with a list - micseydel - Dec-30-2019

I tried simplifying your function for fun:
def grouper(iterable, n, fillvalue='x'):
    codon_lists = zip_longest(*[iter(iterable)]*n, fillvalue=fillvalue)
    return " ".join("".join(codon) for codon in codon_lists)
In general, I'd recommend list and generator comprehensions over reassigning / overwriting your list, as you were doing. In any case it didn't seem relevant to your question...

While it's good your provided code, you should really be excluding code not relevant to the question, and including your attempt at what you're asking for help with. That said, how do you know which codons to replace? The way your question is currently asked, I could answer in a number of ways. If you could give us more detail, we can surely come up with a satisfactory answer.