我有一个字符串
s = "* * * * * * * = a b = c b = * * * * * * * "
我想为每个项目打印!=“*”包含7个项目和7个项目的子字符串,例如:
* * * * * * * = a b = c b = *
* * * * * * = a b = c b = * *
* * * * * = a b = c b = * * *
* * * * = a b = c b = * * * *
* * * = a b = c b = * * * * *
* * = a b = c b = * * * * * *
* = a b = c b = * * * * * * *
如果尝试使用这样的索引:
items = s.split(' ')
for i in items:
s = items.index(i)
start = s - 7
stop = s + 8
print items[start:stop]
问题是,如果元素第二次出现在列表中,脚本会获取列表中第一个外观的索引,你会得到:
* * * * * * * = a b = c b = *
* * * * * * = a b = c b = * *
* * * * * = a b = c b = * * *
* * * * * * * = a b = c b = * etc.
有人可以帮我吗?
答案 0 :(得分:2)
使用enumerate()
,以便同时拥有当前项目及其索引:
items = s.split(' ')
for index, item in enumerate(items):
if item != "*":
print items[index-7:index+8]
注意:如果在集合的开头可能少于7个*
个字符,您可能希望使用稍微不同的最后一行:
print items[max(index-7,0):index+8]