Search code examples
pythonpython-2.7dictionarykeyerror

KeyError: '\n' python 2.7.5


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)

Solution

  • '\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]]