How to replace several characters from string in julia

Viewed 378

I have tried below function. Example:

dna = "ACGTGGTCTTAA"
function to_rna(dna)
    for (nucleotides1, nucleotides2) in zip("GCTA", "CGAU")
        dna = replace(dna, nucleotides1 => nucleotides2)
    end
    return dna
end

Output: "UGGUGGUGUUUU", which is not expected.

Expected output: "UGCACCAGAAUU"

Can somebody point out what went wrong.

1 Answers

You're performing the replacement of each letter in sequence:

julia> function to_rna(dna)
           for (nucleotides1, nucleotides2) in zip("GCTA", "CGAU")
               dna = replace(dna, nucleotides1 => nucleotides2)
               @show nucleotides1 => nucleotides2
               @show dna
           end
           return dna
       end
to_rna (generic function with 1 method)

julia> to_rna(dna)
nucleotides1 => nucleotides2 = 'G' => 'C'
dna = "ACCTCCTCTTAA"
nucleotides1 => nucleotides2 = 'C' => 'G'
dna = "AGGTGGTGTTAA"
nucleotides1 => nucleotides2 = 'T' => 'A'
dna = "AGGAGGAGAAAA"
nucleotides1 => nucleotides2 = 'A' => 'U'
dna = "UGGUGGUGUUUU"
"UGGUGGUGUUUU"

julia> dna
"ACGTGGTCTTAA"

That is, you can't distinguish an RNA C from a DNA C after the first step etc.

You'd want it to work in parallel -- somehow like this:

julia> to_rna2(dna) = map(dna) do nucleotide
           NUCLEOTIDE_MAPPING[nucleotide]
       end
to_rna2 (generic function with 1 method)

julia> NUCLEOTIDE_MAPPING = Dict(n1 => n2 for (n1, n2) in zip("GCTA", "CGAU"))
Dict{Char,Char} with 4 entries:
  'A' => 'U'
  'G' => 'C'
  'T' => 'A'
  'C' => 'G'

julia> to_rna2(dna)
"UGCACCAGAAUU"

This also removes the unnecessary work of iterating over the string four times.

replace is already able to do that by itself -- if you give it an array and pass it multiple replacement arguments:

julia> replace(collect(dna), NUCLEOTIDE_MAPPING...)
12-element Array{Char,1}:
 'U'
 'G'
 'C'
 'A'
 'C'
 'C'
 'A'
 'G'
 'A'
 'A'
 'U'
 'U'

To get back a string instead of an array, you just have to join it again:

julia> replace(collect(dna), NUCLEOTIDE_MAPPING...) |> join
"UGCACCAGAAUU"
Related