1

If I have this line

"he is a good man and he goes every day to a school"

And I want to detect what is between the two words "he""and", so the output will be

is a good man

I tried this

for line in file:
    print line[line.index('he'): line.index('and')]

This code gives the output

he is a good man

How can I do that?

sss
  • 1,307
  • 2
  • 10
  • 16

2 Answers2

2

Try using the command re.search():

import re
s = "he is a good man and he goes every day to a school"
result = re.search('he (.*) and', s)
                    #^-------^ Find string in between 'he' and 'and'

print result.group(1)

This outputs:

>>> 
is a good man
>>> 

Also, if you don't fancy the re module, there are many other methods to do this.

Please have a look here: Find string between two substrings

Community
  • 1
  • 1
logic
  • 1,739
  • 3
  • 16
  • 22
0

Slice is start/from index inclusive and finish/to index exclusive. This is why it excludes 'and' but includes 'he'

for line in file:
    print line[line.index('he') - 1: line.index('and')]