1

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.

2
  • any whole word or a specific word? Commented Mar 5, 2015 at 21:24
  • See the documentation for match objects. Commented Mar 5, 2015 at 21:24

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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())

1 Comment

If you just want the first occurrence, just use re.search().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.