2016-09-19 108 views
0

的Python 3.5字符串索引

这里是我的代码:

str1 = input("Please enter a full sentence: ").lower() 
print("Thank you, You entered:" , str1) 

str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower() 

if str2 in str1: 
    print("That word was found!") 
else: 
    print("Sorry, that word was not found") 

由于它是,它会搜索输入的字(STR2),如果它是在输入(STR1发现(句子))它会说“这个词已被找到”)。如果该单词不在句子中,则会说“该单词未找到”。

我想开发这个,所以当单词被搜索和发现时,它会告诉用户单词(str2)在句子(str1)中的索引位置。例如:如果我有句子(“我喜欢用Python编码”),并搜索单词(“代码”),程序应该说“该单词在索引位置:4”。

顺便说一句,代码不区分大小写,因为它将所有的单词转换成小写的.lower。

如果有人可以给我一些建议,那么这将非常感激!

+0

你使用Python 2.7还是Python 3? – PrestonM

回答

1

您可以取代您的if ... else本:

try: 
    print("That word was found at index %i!"% (str1.split().index(str2) + 1)) 
except ValueError: 
    print("Sorry, that word was not found") 
+0

谢谢,这对我有用。很好,很简单,对原始代码的改变不大,我想要的东西。干杯! :) –

+0

不客气。;-) – trincot

0
print("That word was found at index %i!"% (str1.split().index(str2))) 

这将打印str1中第一次出现str2的索引。
完整的代码是:

str1 = input("Please enter a full sentence: ").lower() 
print("Thank you, You entered:" , str1) 

str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower() 

if str2 in str1: 
    print("That word was found!") 
    print("that word was found in index position: %i!"% (str1.split().index(str2))) 

,str1.index(STR2))
其他: 打印( “对不起,这个词没有找到”)

+1

不完全。 'str1.split().index(str2)' –

+0

是的,无效的语法 –

+0

嗯....我没有得到语法错误....你输入你的输入包围引号吗? – PrestonM

0
str2 = 'abcdefghijklmnopqrstuvwxyz' 
str1 = 'z' 
index = str2.find(str1) 
if index != -1: 
    print 'That word was found in index position:',index 
else: 
    print 'That word was not found' 

这将打印在STR2其中str1指数

+0

我不会命名一个变量'str',并且你可以'从字符串import ascii_lowercase'来得到字母表 –

+0

你是对的,但他显然是python的新手,我不想把他和那个import 。 –

+0

谢谢,这对我有效。但由于某种原因,它并没有给我正确的索引号。例如,如果我为str1给出了“我喜欢Python中的代码”,然后我搜索了“代码”,它告诉我它处于索引位置10?有没有办法来解决这个问题? –

0

您可以使用split()方法:它在字符串值上调用并返回字符串列表。那么你使用index()方法来查找字符串的索引。

str1 = input("Please enter a full sentence: ").lower() 
print("Thank you, You entered:" , str1) 
str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower() 

if str2 in str1: 
    a = str1.split() # you create a list 
    # printing the word and index a.index(str2) 
    print('The ', str2,' was find a the index ', a.index(str2)) 
    print("That word was found!") 
else: 
    print("Sorry, that word was not found")