How to Find Which Position a Word Is in a String

Finding the position of words in a string

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

Find position of word in string

You can use find_in_set() for this:

select find_in_set('lovely', replace('good morning what a lovely day today', ' ', ','))

Yields:

 5

From the documentation:

FIND_IN_SET(str,strlist)

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by , characters.

So basically the logic is to replace space characters with commas, and then use that function.



Related Topics



Leave a reply



Submit