简体   繁体   English

在字符串中搜索多个单词(python)

[英]search multiple words in a string (python)

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?我可以使用.find/.index 或任何其他方法在一个字符串中搜索多个词吗?

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如果我尝试获取第二个词,我将得到 -1,这意味着未找到

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?我可以使用其他方法吗?

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.尝试该代码会产生以下终端 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.试一试,看看它是否符合您的代码精神。

I read this cool trick from a book "confident coding" where I learned how to do stuff like that, here you go:我从一本书“自信的编码”中读到了这个很酷的技巧,我在那里学习了如何做这样的事情,给你 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM