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


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



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

Applying that to your question. We get

import re
a ='\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"'\b(you)\b', str1).start()
# output is 0'\b(you)\b', str2).start()
# output is 3'\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'\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), str).start()
#output is 16