Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find word next to a word in Python [closed]

I would like to find an occurrence of a word in Python and print the word after this word. The words are space separated.

example :

if there is an occurrence of the word "sample" "thisword" in a file . I want to get thisword. I want a regex as the thisword keeps on changing .

like image 817
Vamsi Varanasi Avatar asked Nov 28 '22 09:11

Vamsi Varanasi


1 Answers

python strings have a built in method split that splits the string into a list of words delimited by white space characters (doc), it has parameters for controlling the way it splits the word, you can then search the list for the word you want and return the next index

your_string = "This is a string"
list_of_words = your_string.split()
next_word = list_of_words[list_of_words.index(your_search_word) + 1]
like image 102
crasic Avatar answered Dec 05 '22 14:12

crasic