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 substringseq[:-2](which is'attctg'). Soitakes values like'a','t','t', etc.—these are strings, not integers. - When you try
seq[i*3], Python interpretsi*3as repeating the stringithree times (e.g.,'a'*3becomes'aaa'). You can't use a string as an index for another string—Python expects integers here, hence theTypeError: 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

