与:
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
我想找到关键字在句子中的位置。到目前为止,我有这段代码去掉了标点符号并使所有字母小写:
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''#This code defines punctuation
#This code removes the punctuation
no_punct = ""
for char in sentence:
if char not in punctuations:
no_punct = no_punct + char
no_punct1 =(str.lower (no_punct)
我知道需要一段代码来实际找到单词的位置。
最佳答案
这就是str.find()
是为了:
sentence.find(word)
这将为您提供单词的起始位置(如果它存在,否则 -1),然后您只需将单词的长度添加到它以获得其结尾的索引。
start_index = sentence.find(word)
end_index = start_index + len(word) # if the start_index is not -1
关于python - 查找单词在字符串中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33053641/