Lenna が投稿したように、enumerateはループ中に位置インデックスを追跡する良い方法です。
つまり、text[i-5]
ルックアップはいつでも失敗しますi < 5
。代わりに、スライスを使用して の周りの範囲にアクセスしてみてくださいi
。
>>> test_text = "lorem ipsum dolor sit amet"
>>> for i, c in enumerate(test_text):
print repr(c), "is surrounded by", repr(test_text[i-5:i+5])
'l' is surrounded by ''
'o' is surrounded by ''
'r' is surrounded by ''
'e' is surrounded by ''
'm' is surrounded by ''
' ' is surrounded by 'lorem ipsu'
'i' is surrounded by 'orem ipsum'
'p' is surrounded by 'rem ipsum '
's' is surrounded by 'em ipsum d'
'u' is surrounded by 'm ipsum do'
'm' is surrounded by ' ipsum dol'
' ' is surrounded by 'ipsum dolo'
'd' is surrounded by 'psum dolor'
'o' is surrounded by 'sum dolor '
'l' is surrounded by 'um dolor s'
'o' is surrounded by 'm dolor si'
'r' is surrounded by ' dolor sit'
' ' is surrounded by 'dolor sit '
's' is surrounded by 'olor sit a'
'i' is surrounded by 'lor sit am'
't' is surrounded by 'or sit ame'
' ' is surrounded by 'r sit amet'
'a' is surrounded by ' sit amet'
'm' is surrounded by 'sit amet'
'e' is surrounded by 'it amet'
't' is surrounded by 't amet'