Question

I have a python string called line that I've split. line is a recurring string. I'm searching through an excel file and printing out each line that contains a specific word, i'll call it search which is a term that the user inputs. If the line doesn't contain search then it doesn't get printed.

I split the line, and printed out the search_index (index of the search term in the line).

s=line.split()
search_index = s.index(search) if inflected in s else "not in this line"
print(search_index)

If it doesn't exist in the line then the log will say "not in this line" instead of a number since it was crashing whe nI didn't include that.

What I awnt to do is join this split back together, but from a range with the searched term being teh middle. So, something like

new_line=[search_index - 5:search_index + 5]

but not sure if that's right since it gives me an error on the webpage of "syntax invalid"

How should this be properly done?

Was it helpful?

Solution

I think you have a typo (missing line before your range [:]) but there's another thing as well. If your search_index has been assigned a string, you can't subtract or add 5 to it.

I'm not sure of the context so you'll have to tweak this to your needs but this addresses those issues:

s=line.split()
if inflected in s:
    search_index = s.index(search)
    new_line = line[search_index-5:search_index+5]
else:
    print("not in this line")

OTHER TIPS

When you get the attribute of a list, you always have to put the name of the list before how you are calling it:

>>> line = 'hello world!'
>>> search_index = 3
>>> [search_index-3:search_index+3]
  File "<stdin>", line 1
    [search_index-3:search_index+3]
                   ^
SyntaxError: invalid syntax
>>> line[search_index-3:search_index+3]
'hello '
>>> 

Therefore, instead of new_line = [search_index-5:search_index+5], use new_line = line[search_index-5:search_index+5].

Here is another example:

>>> line = 'Hello this is django on python'
>>> line = line.split()
>>> search_index = line.index('django')
>>> new_line = [search_index - 2:search_index + 2]
  File "<stdin>", line 1
    new_line = [search_index - 2:search_index + 2]
                                         ^
SyntaxError: invalid syntax
>>> new_line = line[search_index - 2:search_index + 2]
>>> new_line
['this', 'is', 'django', 'on']
>>> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top