jurek
jurek

Reputation: 33

How to find whole string using find()

How to find whole string using find() function?

For example my input:

word = 'banana'

sentence1 = 'Hello, I very like eat banana'
>True

sentence2 = ' Hello, I very like eat banana1'
>False

I want to use find() function, because I want get start and end position of this string.

For example:

loc = sentence1.find(word)

Upvotes: 1

Views: 169

Answers (1)

Sam Collins
Sam Collins

Reputation: 483

An overkill solution might be to use regex. Your expression could use work boundaries which fixes the problem with the 1 added on.

import re
text = 'Hello, I very like eat banana'
start, end = re.search(r'\bbanana\b', text).span()

span returns a tuple so you can assign it to one variable and it will be like (20, 40) which you can access using [0] etc or into two variables like above.

If you do this often I recommend using re.compile() on your regex first.

Upvotes: 1

Related Questions