Apologies if this has already been asked. Is there a way in Python 3x to search for a whole word in a string and return its starting index?
Any help would be greatly appreciated.
Apologies if this has already been asked. Is there a way in Python 3x to search for a whole word in a string and return its starting index?
Any help would be greatly appreciated.
Yes, with a regex and word boundary anchors:
>>> import re
>>> s = "rebar bar barbed"
>>> regex = re.compile(r"\bbar\b")
>>> for match in regex.finditer(s):
... print(match.group(), match.start(), match.end())
...
bar 6 9
The \b anchors make sure that only entire words can match. If you're dealing with non-ASCII words, use re.UNICODE to compile the regex, otherwise \b won't work as expected, at least not in Python 2.
If you just want the first occurrence, you can use re.finditer and next.
s = "foo bar foobar"
import re
m = next(re.finditer(r"\bfoobar\b",s),"")
if m:
print(m.start())
Or as @Tim Pietzcker commented use re.search:
import re
m = re.search(r"\bfoobar\b",s)
if m:
print(m.start())
re.search().