新同學來了...
我只是想在字串中查找單詞。我可以使用 .find/.index 或任何其他方法在一個字串中搜索多個詞嗎?
ex = "welcome to my question. you are welcome to be here"
print(ex.find("welcome"))
result = 0
如果我嘗試獲取第二個詞,我將得到 -1,這意味著未找到
ex = "welcome to my question. you are welcome to be here"
print(ex.find("welcome", 21, 0))
result = -1
我可以使用其他方法嗎?
uj5u.com熱心網友回復:
您看起來好像在正確的軌道上,但在使用查找操作時得到了一些不正確的引數。使用您的示例字串,以下是代碼的調整版本。
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
嘗試該代碼會產生以下終端輸出。
@Dev:~/Python_Programs/Find$ python3 Find.py
welcome was found at position: 0
welcome was found at position: 32
試一試,看看它是否符合您的代碼精神。
uj5u.com熱心網友回復:
我從一本書“自信的編碼”中讀到了這個很酷的技巧,在那里我學會了如何做這樣的事情,給你:
# 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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533925.html
標籤:Python细绳
上一篇:str.get()在str.split之后沒有抓取正確的元素
下一篇:更改元組串列中的元組
