字符串索引

时间:2016-09-19 21:36:38

标签: string indexing python-3.5

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(一个句子)),它将说“已找到单词”)。如果单词不在句子中,则会说“找不到单词”。

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

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

如果有人能就此提出一些建议,那将非常感激!

4 个答案:

答案 0 :(得分: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")

答案 1 :(得分: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))
    其他:         打印(“抱歉,找不到该词”)

答案 2 :(得分: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的索引

答案 3 :(得分: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")