Python 3.x 带字符串的作业

Python 3.x 带字符串的作业,python-3.x,string,reverse,Python 3.x,String,Reverse,大家好,我有一个家庭作业,我得到一个字符串,基本上我应该更改其中的字母,然后将其向后返回: A->T T->A G->C C->G 这是我的密码: def dnaComplement(s): newWord = "" for x in s: if x == "T": newWord.join('A') elif x == "A": newWord.join('T') elif x

大家好,我有一个家庭作业,我得到一个字符串,基本上我应该更改其中的字母,然后将其向后返回:

A->T

T->A

G->C

C->G

这是我的密码:


def dnaComplement(s):
    newWord = ""

    for x in s:
        if x == "T":
            newWord.join('A')
        elif x == "A":
            newWord.join('T')
        elif x == "C":
            newWord.join('G')
        elif x == "G":
            newWord.join('C')
    return newWord[::-1]



输入是:ACCGGGTTTT

到目前为止,您的努力遇到了一个小问题

您正在使用newWord.join'X'尝试将新字符添加到字符串中。这与您尝试使用它的方式不同。再次阅读中的join函数

相反,您可以使用+=运算符将字符追加到新词字符串的末尾:

然后,您的代码变成:

def dnaComplement(s):
    newWord = ""

    for x in s:
      if x == "T":
        newWord += 'A'
      elif x == "A":
        newWord += 'T'
      elif x == "C":
        newWord += 'G'
      elif x == "G":
        newWord += 'C'

    return newWord[::-1]

print(dnaComplement('ACCGGGTTTT'))
输出:

AAAACCCGGT
这与TGGCCCAAA相反,它存储在newWord中,直到您从dnaComplement返回它。

newWord.join。。。不会更改network的值,而是返回一个新字符串

因此,首先,您需要执行类似network=newWord.join的操作

也就是说,这是一种更干净的方式:

d = {'T': 'A',
     'A': 'T',
     'C': 'G',
     'G': 'C'
}

def dnaComplement(s):
    return ''.join(d[x] for x in s[::-1])
新词,加入。。。不会更改网络的值,因此首先,您需要执行类似network=newWord.join的操作。。。。
d = {'T': 'A',
     'A': 'T',
     'C': 'G',
     'G': 'C'
}

def dnaComplement(s):
    return ''.join(d[x] for x in s[::-1])