How to replace multiple characters in a string using Julia

I am essentially trying to solve this problem: http://rosalind.info/problems/revc/

I want to replace all occurrences of A, C, G, T with their compliments T, G, C, A .. in other words, all A will be replaced by T, all C with G, etc.

Earlier, I used the replace() function to replace all occurrences of “T” with “U” and was hoping that the replace function would accept a list of characters to replace with another list of characters, but I was not able to make it work, so it might not have that functionality.

I know that I can easily solve this problem with the BioJulia package and did it using the following:

 # creating complementary strand of DNA # reverse the string # find the complementary nucleotide using Bio.Seq s = dna"AAAACCCGGT" t = reverse(complement(s)) println("$t") 

But I do not want to rely on the package.

Here is the code that I have, if someone can direct me in the right direction, that will be great.

 # creating complementary strand of DNA # reverse the string # find the complementary nucleotide s = open("nt.txt") # open file containing sequence t = reverse(s) # reverse the sequence final = replace(t, r'[ACGT]', '[TGCA]') # this is probably incorrect # replace characters ACGT with TGCA println("$final") 
+6
source share
1 answer

It seems that replace does not yet make translations, like, say, tr in Bash. Instead, here are a couple of approaches using word matching (the BioJulia package also seems to use similar dictionaries):

 compliments = Dict('A' => 'T', 'C' => 'G', 'G' => 'C', 'T' => 'A') 

Then, if str = "AAAACCCGGT" , you can use join as follows:

 julia> join([compliments[c] for c in str]) "TTTTGGGCCA" 

Another approach might be to use a function and map :

 function translate(c) compliments[c] end 

Then:

 julia> map(translate, str) "TTTTGGGCCA" 

Strings are exterminated objects in Julia; each of these approaches reads one character, in turn, c and passes it to the dictionary to return a free character. A new line is created from these free characters.

Julia strings are also immutable: you cannot change characters around, but you need to create a new string.

+5
source

All Articles