Home > database >  search multiple words in a string (python)
search multiple words in a string (python)

Time:11-14

New learner here...

i just trying to find word in a string. can i search multiple words in one string using .find/.index or any other method?

ex = "welcome to my question. you are welcome to be here"
print(ex.find("welcome"))
result = 0

and if i try get the second word i will get -1 which mean not found

ex = "welcome to my question. you are welcome to be here"
print(ex.find("welcome", 21, 0))
result = -1

is there any other method i can use?

CodePudding user response:

You look like you were on the right track but got some of the parameters incorrect in using the find operation. Using your sample string, following is a tweaked version of the code.

ex = "welcome to my question. you are welcome to be here"

x = 0

while True:
    x = ex.find("welcome", x, len(ex))
    if x == -1:
        break
    print("welcome was found at position:", x)
    x = x   1  #Makes sure that searches are for subsequent string matches

Trying out that code resulted in the following terminal output.

@Dev:~/Python_Programs/Find$ python3 Find.py 
welcome was found at position: 0
welcome was found at position: 32

Give that a try and see if it meets the spirit of your code.

CodePudding user response:

I read this cool trick from a book "confident coding" where I learned how to do stuff like that, here you go:

# very important
import re

example = "Hello, in this string we will extract 2 numbers, number 1 and 
number 2"

result_1 = re.search("Hello, in this string we will extract 2 numbers, 
number (.*) and number (.*)", example)

# we want to print it out

print(result_1.group(1)) # prints out "1"

print(result_1.group(2)) # prints out "2"
  • Related