以下是在字符串中按索引查找单词的代码示例:
def find_word_by_index(string, index):
word = ""
start = index
end = index
# Find the start index of the word
while start > 0 and string[start-1].isalpha():
start -= 1
# Find the end index of the word
while end < len(string)-1 and string[end+1].isalpha():
end += 1
# Extract the word from the string
word = string[start:end+1]
return word
# Example usage
sentence = "Hello, how are you?"
index = 8
word = find_word_by_index(sentence, index)
print(word) # Output: "how"
此示例中的find_word_by_index
函数接受一个字符串和索引作为参数,并根据该索引在字符串中找到包含该索引的单词。它首先从给定索引开始,向前搜索直到找到单词的起始位置,并从给定索引开始,向后搜索直到找到单词的末尾位置。然后,它从字符串中提取出该单词,并将其作为结果返回。
在上述示例中,我们使用句子"Hello, how are you?"和索引8来查找单词。根据给定的索引,我们找到了单词"how",并将其作为结果打印出来。
上一篇:按照索引数组对对象数组进行排序