Ad

Python - Return Starting Index Of Exact Match To Sub-string

- 1 answer

I need to find the starting index of a string when there is an exact match to a sub-string.

line = "Your family and You are invited to my party"

I want to find the starting index of Youi.e. 16

I have tried

line.find("You")

however that returns 0

Then I tried,

import re
print(re.findall('\\bYou\\b', line))

But it returns a list with the sub-string in it

["You"]
Ad

Answer

If you are fine using a regex then this answer should address your issue.

Applying that to your question. We get

import re
a = re.search(r'\b(you)\b', 'Your family and you are invited to the party')
print a.start()

Which gives 16

Does this work for all possible positions of "you"? (start, middle and end)? Let's check

str1 = "you hi"
str2 = "hi you"
str3 = "hi you hi"
re.search(r'\b(you)\b', str1).start()
# output is 0
re.search(r'\b(you)\b', str2).start()
# output is 3
re.search(r'\b(you)\b', str3).start()
# output is 3

UPDATE 1: Case insensitive matching

In case you want a case insensitive match use re.IGNORECASE like this

re.search(r'\b(you)\b', str3, re.IGNORECASE).start()

UPDATE 2: Passing a variable instead of hardcoded string in the regex

str = "Your family and you are invited to the party"
word_to_search = "you"
re_string = r"\b({})\b".format(word_to_search)
re.search(re_string, str).start()
#output is 16
Ad
source: stackoverflow.com
Ad