9

My Task

I am trying to find the position of words appearing in a string using regex

Code

import re

# A random string

mystr = "there not what is jake can do for you ask what you play do for spare jake".upper() 

match = re.search(r"[^a-zA-Z](jake)[^a-zA-Z]", mystr)

print match.start(1)

Output

18

Expected output

I would expect my output to contain the positions of the string jake:

5, 17

EDIT: To clarify, I'm trying to identify the position of words. I believe what I have done is found the index and am unsure how to make it work as I expect

ThatOneNoob
  • 3,332
  • 6
  • 25
  • 45

2 Answers2

7

To get the "ordinal" positions of search string jake in the input string use the following approach:

mystr = "there not what is jake can do for you ask what you play do for spare jake"
search_str = 'jake'

result = [i+1 for i,w in enumerate(mystr.split()) if w.lower() == search_str]
print(result)  

The output:

[5, 17]

  • enumerate(mystr.split()) - to get enumerated object (pairs of items with their positions/indices)

  • w.lower() == search_str - if a word is equal to search string

RomanPerekhrest
  • 75,918
  • 4
  • 51
  • 91
4

Try this way:

mystr = "there not what is jake can do for you ask what you play do for spare jake"
result = [index+1 for index,word in enumerate(mystr.split()) if word=='jake']
result

Output:

[5, 17]
Tiny.D
  • 6,266
  • 2
  • 14
  • 20