Python GCSE - 使用列表

Python GCSE - Using Lists

在接下来的几周内,我将参加计算机科学 GCSE。作为一名应用程序开发人员,我真的很需要这个 GCSE,所以任何帮助都会很棒!对于我的 GCSE 的编码部分,我需要创建一个 python 脚本,允许用户键入一个字符串,然后在该字符串中搜索一个词。从那里开始,脚本必须 return 该搜索词的所有位置。我这里有一些示例代码:

userinp = input("Please type a sentence: ")
list1[]
string1 = userinp.split()
for x in string1:
        list1.insert(x,string1[x])
search = input("Search for a word: ")
for x in range(len(string1)):
         if search in list1:
                   print("Word found at index:",x)

请记住,此代码可能无法 100% 工作,因为它是在 phone.

上键入的

实际任务是回忆单词的所有位置,但经过无数次尝试,我无法让它打印同一个单词的其他索引。例如,如果字符串是 "Hello my name is Jack and my favourite food is apples" 而我搜索 'my',程序将必须 return 在索引 2 和 7 处找到该词。

由于这是在 phone 上输入的,实际问题可能还不清楚,如果是这样,请直接评论。否则,任何帮助都会很棒!

试试这个,

userinp = raw_input("Please type a sentence: ")
words = userinp.split(' ')
search = raw_input("Search for a word: ")
for idx, word in enumerate(words):
    if search == word:
        print("Word found at index:", idx)

希望对您有所帮助。