Python 字典无法处理txt文件中的DNA字符串

Python 字典无法处理txt文件中的DNA字符串,python,dictionary,compiler-errors,bioinformatics,dna-sequence,Python,Dictionary,Compiler Errors,Bioinformatics,Dna Sequence,当我使用文本文件中的DNA字符串时,使用字典的函数会返回KeyFile错误“\n”,但当我手动键入DNA字符串时则不会返回该错误: DNA = open(r"C:\Users\CP\Desktop\Python\rosalind_revc.txt","r") DNA = DNA.read() DNA.replace(' ','') print(DNA) # Output works when I manually type a DNA string, s

当我使用文本文件中的DNA字符串时,使用字典的函数会返回KeyFile错误“\n”,但当我手动键入DNA字符串时则不会返回该错误:


DNA = open(r"C:\Users\CP\Desktop\Python\rosalind_revc.txt","r")
DNA = DNA.read()
DNA.replace(' ','')
print(DNA)
# Output works when I manually type a DNA string, such as the one below in the comment
# DNA = "TCAGCAT"

def complement(s): 
    
    # Create a dictionary with all the complementary base pairings
    basecomplement = {'A':'T','C':'G','G':'C','T':'A'}
    
    # Turn the input DNA into a list
    letters = list(s)
    
    # Use the dictionary to replace each list element
    n = [basecomplement[b] for b in letters]
    
    # Make the function return the list as a string
    # We want no spaces in the new DNA string, so there are no spaces inside
    # the quotation marks--that's where the "separator" is.
    return ''.join(n)

def revcom(s):
    return(complement(s[::-1]))

DNA_revcom = revcom(DNA)

print(DNA_revcom)


我是Python编程新手,所以我非常感谢您的反馈

与手动键入的字符串不同,文件中的行有一个。因此,您需要删除换行符,您可以这样做:

DNA = DNA.read().rstrip()

这回答了你的问题吗?感谢您提供的学习机会。这个建议彻底解决了我的问题。不客气!如果我的答案解决了你的问题,你可以。哈哈,我刚刚学会如何在StackOverflow上“接受解决方案”。谢谢