You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 2.7字符串索引报错求助:TypeError问题排查

Hey there! Let's figure out why this error is happening and get your code working as intended.

What's Causing the TypeError?

Let's break down your original code step by step:

seq = 'attctgta'
for i in seq[:-2]:
    if seq[i*3] == 'a' and seq[i*3+1] == 't' and seq[i*3+2] == 't':
        print 'I'
  • The line for i in seq[:-2] iterates over each character in the substring seq[:-2] (which is 'attctg'). So i takes values like 'a', 't', 't', etc.—these are strings, not integers.
  • When you try seq[i*3], Python interprets i*3 as repeating the string i three times (e.g., 'a'*3 becomes 'aaa'). You can't use a string as an index for another string—Python expects integers here, hence the TypeError: string indices must be integers, not str.

Fixing the Code

It looks like you want to check either the first three characters of seq, or all consecutive triplets of characters to see if they match 'att'. Here are solutions for both cases:

Case 1: Check only the first three characters

If you just need to verify the first three characters are 'att', you don't need a loop at all:

seq = 'attctgta'
if seq[:3] == 'att':
    print 'I'

Case 2: Check all consecutive triplets

If you want to scan the entire string for every occurrence of the triplet 'att', loop over integer indices instead of characters:

seq = 'attctgta'
# Iterate over starting indices where we can fit a 3-character triplet
for i in range(len(seq) - 2):
    # Extract the 3-character substring starting at index i
    triplet = seq[i:i+3]
    if triplet == 'att':
        print 'I'

This code uses range(len(seq) - 2) to generate valid starting indices (from 0 to 5, since len(seq) is 8—8-2=6, so range(6) gives 0-5). For each index, we slice the string to get the triplet and check if it's 'att'.

内容的提问来源于stack exchange,提问作者Brian Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:10:01