python for in语句 index_使用for循环查找句子中的单词及其索引位置
我正在編寫一個代碼,提示用戶輸入一個句子,然后定義為str1,然后提示輸入一個定義為str2的單詞。
例如:Please enter a sentence: i like to code in python and code things
Thank you, you entered: i like to code in python and code things
Please enter a word: code
我想使用for循環在str1中查找str2,以打印是否找到該單詞,如果找到該單詞,則打印str2的索引位置。
目前我有以下代碼:str1Input = input("Please enter a sentence: ")
print("Thank you, you entered: ",str1Input)
str1 = str1Input.split()
str2 = input("Please enter a word: ")
if str2 in str1:
for str2 in str1:
print("That word was found at index position", str1.index(str2)+1)
else:
print("Sorry that word was not found")
盡管,結果似乎是打印是否找到索引位置,但隨后打印句子中每個單詞的索引位置。另外,如果我正在搜索某個在該句子中出現兩次的單詞,它只會打印該單詞在該句子中第一次出現時的索引位置,例如:Please enter a sentence: i like to code in python and code things
Please enter a word: code
Thank you, you entered: i like to code in python and code things
That word was found at index position: 1
That word was found at index position: 2
That word was found at index position: 3
That word was found at index position: 4
That word was found at index position: 5
That word was found at index position: 6
That word was found at index position: 7
That word was found at index position: 4
That word was found at index position: 9
如果有人能幫助我和其他人嘗試類似的事情,這將是非常有幫助的!
總結
以上是生活随笔為你收集整理的python for in语句 index_使用for循环查找句子中的单词及其索引位置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python类定义中、对象字符串的特殊方
- 下一篇: miniui页面移动的时候透明_【H5】