2017-02-02 49 views
-1

我已經爲此做了一個開始,它迄今爲止完美,但它沒有找到無論我使用的方法如何,一個單詞的位置。我已經研究並且迄今爲止沒有發現任何東西,請幫助。我需要創建一個Python腳本,它允許你輸入一個單詞,並在你所做的一個句子中找到這個單詞的位置

print ("Enter your sentence here.") 
#This will ensure that the person knows to input a sentence. 
sentence = input() 
#This will allow the person to input a sentence. 
s = sentence.split() 
#This will allow me to split the sentence. 
positions = [s.index(x)+1 for x in s] 
#This will change the first position from 0 to 1. 
print ("Which word would you like to find in this sentence?") 
#This will allow the person to write a word in their sentence. 
word = input() 
#This allows the person to input the word. 
print (positions) 
+0

複製http://stackoverflow.com/questions/21842885/python-find-a-substring-in-a-string並返回索引的子字符串 –

+1

可能重複[Python:查找字符串內的一個詞](http://stackoverflow.com/questions/24103522/python-find-a-word-within -a弦) – jkalden

回答

1
print ("Enter your sentence here.") 
#This will ensure that the person knows to input a sentence. 
sentence = input() 
#This will allow the person to input a sentence. 
s = sentence.split() 
#This will allow me to split the sentence. 
print ("Which word would you like to find in this sentence?") 
#This will allow the person to write a word in their sentence. 
word = input() 
#This allows the person to input the word. 
print(s.index(word) + 1) 

您可以在年底額外的索引位置添加。

0

您還可以使用枚舉打印在句子單詞和他們的立場:

print "enter sentence" 
sentence=raw_input() 
print "enter word" 
word=raw_input() 
s=sentence.split() 
for index, w in enumerate(s): 
    if w==word: 
     print w, index 
相關問題