为什么我的 python 计数器不给我一个范围内的特定字符?

Why isn't my python counter giving me specific characters from a range?

我需要计算字母 'c' 或 'g' 每 3 个字符出现的次数。我的文件是一串 DNA 碱基。这是我目前所拥有的,但是当我尝试 运行 它时,它卡住了并且没有给我答案!

with open("my file.txt","r+") as file:
    GC_content = file.read()
c_count = 0
g_count = 0
for i in range(0, len(GC_content), 3):
    if GC_content[i] == "g":
        g3 = g_count + 1
    if GC_content[i] == "c":
        c3 = c_count + 1

print(g3)
print(c3)

我做错了什么?我是新手!

您必须增加计数器:

c_count = 0
g_count = 0
for i in range(0, len(GC_content), 3):
    if GC_content[i] == "g":
        g_count += 1
    if GC_content[i] == "c":
        c_count += 1

print(g_count)
print(c_count)

但是,使用字符串切片可以更简洁:

print(GC_content[::3].count('g'))
print(GC_content[::3].count('c'))