开发者

Python:How can you get a substring out of string without indices?

开发者 https://www.devze.com 2023-02-16 00:51 出处:网络
I have a string s = \"* * * * * * * = a b = c b = * * * * * * * \" and I would like to print for every item != \"*\" a substring containing 7 items before and 7 after, e.g.:

I have a string

s = "* * * * * * * = a b = c b = * * * * * * * "

and I would like to print for every item != "*" a substring containing 7 items before and 7 after, e.g.:

* * * * * * * = 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 = * * * * * * *

If tried using the index like this:

items = s.split(' ')
   for i in items:
       s = items.index(i)
       start = s - 7
       stop = s + 8
       print items[start:stop]

The problem is that if an element appears in the list a second time, the script takes the index of the first appearance in the list and you get this:

* * * * * * * = a b = c b = * 
* * * * * * = a b = c b = * *
* * * * * = a b = c b = * * *
* * * * * * * = a b = c b = *  etc.

Can anyone please help me on this?


Use enumerate() so that you have both the current item and its index available:

items = s.split(' ')
for index, item in enumerate(items):
    if item != "*":
        print items[index-7:index+8]

Note: if it's possible for there to be fewer than 7 * characters at the start of the set, you may want to use a slightly different final line:

        print items[max(index-7,0):index+8]
0

精彩评论

暂无评论...
验证码 换一张
取 消