haystack = "lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor it is no wonder that nike is one of the largest brands in the world is not lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor" needle = "nike342" lookahead = 7 # Number of tokens to show before "nike" tokens = haystack.split(" ") # Split string into a list of tokens found_index = -1 # Represents the index of the token. Initialize to -1 and assume it doesn't exist. # Loop through tokens and compare each to the needle. If we find the needle, rememeber the index and break out of the loop found_index = tokens.index(needle) try: found_index = tokens.index(needle) # Get the max of the found index minus the number of words to show before the needle, and 0 found_index = max(found_index - lookahead, 0) # Create a sub list of the tokens from the found_index and end, then join those terms back together with a space. snippet = " ".join(tokens[found_index:len(tokens)]) except ValueError: snippet = "" # No snippet or whatever error handling you are going to do print snippet
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question