سؤال

I have a dictonairy I want to compare to my string, for the each ke in the dictoniary which matches that in the string I wish to convert the string character to that of the dictoniary

I want to compare my dictionary to my string character by character and when they match replace the strings character with the value of the dictionary's match e.g. if A is in the string it will match to A in the dictionary and be replaced with T which is written to the file line2_u_rev_comp. However the error KeyError: '\n' occurs instead. What is this signaling and how can it be removed?

REV_COMP = {
'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C',
'N': 'N',
'U': 'A'
}
tbl = REV_COMP
line2_u_rev_comp = [tbl[k] for k in line2_u_rev[::-1]]
''.join(line2_u_rev_comp)
هل كانت مفيدة؟

المحلول

'\n' means new line, and you can get rid of it (and other extraneous whitespace) using str.strip, e.g.:

line2_u_rev_comp = [tbl[k] for k in line2_u_rev.strip()[::-1]]

نصائح أخرى

line2_u_rev_comp = [tbl.get(k,k)  ... ]

this will either get it from the dictionary or return itself

The problem is the tbl[k] but you don't check if the key exists in the dict, if not you need to return k it self.

you also need to reverse again the list since your for statement is reversed.

Try this code:

    line2_u_rev = "MY TEST IS THIS"
    REV_COMP = {
    'A': 'T',
    'T': 'A',
    'C': 'G',
    'G': 'C',
    'N': 'N',
    'U': 'A'
    }
    tbl = REV_COMP
    line2_u_rev_comp = [tbl[k] if k in tbl else k for k in line2_u_rev[::-1]][::-1]
    print ''.join(line2_u_rev_comp)

Output:

MY AESA IS AHIS

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top