python - 查找单词在字符串中的位置

标签 python string python-3.x find

与:

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/

相关文章:

python - 十进制转 JSON

regex - R 中按条件分割字符串

php - 如何删除某个起始符号及其结束符号,但不删除内容?

python - 在 python 3 上使用 tkinter 打开图像

python-3.x - PySpark python 错误 : Exception: Java gateway process exited before sending the driver its port number

python - 使用NLTK的编码问题

python - 有效地将索引附加到 Python 中的重复字符串

python - 如何查找两列中的值是否在 Pandas 数据框中反向出现

python - 对字符串进行切片并返回拼接后的字符串

python - 无法访问 python 3 中的(嵌套)枚举类型(proto3)