Problem with my Python code: IndexError: string index out of range

Problem with my Python code: IndexError: string index out of range

最近我在进行一项 python 挑战,我需要创建一个能够将 DNA 转录为 mRNA 的函数,但每次我 运行 代码都会收到相同的错误消息:

如果 dna[y] == "A": IndexError: 字符串索引超出范围

谁能帮帮我?下面是我的代码示例。

global y
y = 0
global rna
rna = ""
def dna_to_rna(dna):
    global y
    global rna
    for i in range(len(dna)):
        if dna[y] == "A":
            rna += "U"
        elif dna[y] == "T":
            rna += "A"
        elif dna[y] == "G":
            rna += "C"
        else:
            rna += "G"
        y += 1
    return rna  

你有很多额外的变量,你的代码中不需要 'global' 修饰符。我已经对您的代码进行了一些重新格式化,试试这个:

def dna_to_rna(dna: str) -> str:
  rna = ""
  for i in range(len(dna)):
      if dna[i] == "A":
          rna += "U"
      elif dna[i] == "T":
          rna += "A"
      elif dna[i] == "G":
          rna += "C"
      elif dna[i] == "C":
          rna += "G"
      else:
          return "Invalid Sequence!"
  return rna