Erj*_*001 5 python string find python-3.x
附:
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
Run Code Online (Sandbox Code Playgroud)
我想在句子中找到关键字的位置.到目前为止,我有这个代码摆脱标点符号并使所有字母小写:
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)
Run Code Online (Sandbox Code Playgroud)
我知道需要一段实际找到该单词位置的代码.
Kas*_*mvd 15
这str.find()是为了什么:
sentence.find(word)
Run Code Online (Sandbox Code Playgroud)
这将为您提供单词的起始位置(如果存在,否则为-1),然后您可以将单词的长度添加到其中以获得其结尾的索引.
start_index = sentence.find(word)
end_index = start_index + len(word) # if the start_index is not -1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28099 次 |
| 最近记录: |