正如 Lenna 所发布的,枚举是在循环时跟踪位置索引的好方法。
也就是说,您的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'