日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python for in语句 index_使用for循环查找句子中的单词及其索引位置

發(fā)布時間:2024/1/23 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python for in语句 index_使用for循环查找句子中的单词及其索引位置 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

我正在編寫一個代碼,提示用戶輸入一個句子,然后定義為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循環(huán)在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")

盡管,結果似乎是打印是否找到索引位置,但隨后打印句子中每個單詞的索引位置。另外,如果我正在搜索某個在該句子中出現(xiàn)兩次的單詞,它只會打印該單詞在該句子中第一次出現(xiàn)時的索引位置,例如: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循环查找句子中的单词及其索引位置的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。