I have written a function, which takes aligned DNA sequences and replaces "-" with "Z" if the "-" is both preceded and followed by other bases. The goal is to make those bases a "Z" so I can differentiate unsequenced regions of a genome from insertions/deletions. Here's the function:
def find_insertion_deletion(sequence):
pattern = r'[A-Z]+-+(?=[A-Z]+)'
new_sequence = re.sub(pattern, lambda x: x.group().replace('-', 'Z'), sequence)
return new_sequence
This is obviously using regex to find the pattern and then make the replacements. He's an example of how it works.
sequence = '-----------AGCATCGACGTCTAGTAC---CGTACGTA--CGTACGTAGCTA-GCTAGCTAGCTGATCGATGCTAGCA---------------'
new_sequence = find_insertion_deletion(sequence)
output:
new_sequence = '-----------AGCATCGACGTCTAGTACZZZCGTACGTAZZCGTACGTAGCTAZGCTAGCTAGCTGATCGATGCTAGCA---------------'
It works exactly how I want it to, but it's very slow when running this on many sequences in an alignment. Is there a way I can speed this up by a significant amount? I assumed regex would be the fastest way, but maybe there's another way I'm not aware of..
Thanks!