Python последовательность обеспечивает метод index
. Он дает вам индекс элемента или вызывает ошибку, если элемент не находится в последовательности. В строках он позволяет находить подстроки.
>>> 'hello world'.index('world')
6
>>> 'hello world'.index('word')
ValueError: substring not found
В принципе, вы должны добавить ввод для предложения и слова для поиска. Вот и все.
print("Insert sentence without punctuation...")
sentence=input() # get input, store it to name `sentence`
print("Insert word to find...")
word=input()
try:
idx = sentence.index(word)
except ValueError: # so it wasn't in the sentence after all...
print('Word', word, 'not in sentence', repr(sentence))
else: # if we get here, IndexError was NOT thrown
print('Word', word, 'first occurs at position', idx)
Здесь есть некоторые оговорки, например, «fooworldbar» также будет соответствовать. Правильное обращение с такими вещами зависит от того, что именно нужно. Я предполагаю, что вы действительно хотите слово позиций.
Если вам нужны позиции в значении «в n
го слова», вы должны преобразовать фразу в список слов. str.split
делает. Затем вы можете снова работать с index
. Кроме того, если вы хотите все позиции, вы должны позвонить в индекс повторно.
print("Insert sentence without punctuation...")
sentence = input() # get input, store it to name `sentence`
words = sentence.split() # split at whitespace, creating a list of words
print("Insert word to find...")
word=input()
positions, idx = [], -1
while idx < len(words):
try:
idx = words.index(word, idx+1)
except ValueError: # so it wasn't in the rest of the sentence after all...
break
else: # if we get here, IndexError was NOT thrown
positions.append(idx) # store the index to list of positions
# if we are here, we have searched through the whole string
if positions: # positions is not an empty list, so we have found some
print('Word', word, 'appears at positions', ', '.join(str(pos) for pos in positions))
else:
print('Word', word, 'is not in the sentence')
Когда вы ожидаете ' 'слово' == 'COUNTRY'', чтобы быть правдой? Вы имели в виду 'if word == 'COUNTRY''? – doctorlove
Это звучит как сложная задача за такой короткий промежуток времени. –
этот код абсолютно бесполезен. вы когда-нибудь запускали этот код? не могли бы вы рассказать нам, какая часть этого кода не работает и каким образом? – pt12lol