Python:获取列表的索引

时间:2017-09-12 01:38:05

标签: python list loops

我正在尝试创建一个程序,它将输入一个句子和一个单词并检查该单词的句子并返回单词开头的索引 即

sentence = "random set of words" 
     word = "of"
     result = 9

这就是我试过的

sentence = (input("Enter a sentence: "))
word = (input("Enter a Word: "))

result = sentence.split()

for x in sentence:
  if x == (word):
    boom = enumerate(word)
print(boom)

2 个答案:

答案 0 :(得分:1)

假设这个词只出现一次,我就这样做:

sentence = sentence.split(word)
sentence[0] = sentence[0].replace(" ","")
result = len(sentence[0])

答案 1 :(得分:1)

只需使用index()

a =" aa bb cc"

b =" bb"

打印a.index(b)

如果OP希望它只计算字母:

a =" aa bb cc"

b =" bb"

index_t = a.index(b)

real_index = index_t - a [:index_t] .count('')