首页 > 解决方案 > 如何编写一个 python 程序,打印出所有至少三个字符长的子字符串?

问题描述

我需要编写程序,它打印出所有至少三个字符长的子字符串,并且以用户指定的字符开头。这是一个应该如何工作的示例:

Please type in a word: mammoth
Please type in a character: m
mam
mmo
mot

我的代码看起来像这样,它不能正常工作(它只显示 1 个子字符串):

word = word = input("Please type in a word: ")
character = input("Please type in a character: ") 
index = word.find(character)
while True:
    if index!=-1 and len(word)>=index+3:
        print(word[index:index+3])
        break

标签: pythonstringfindsubstring

解决方案


进入后跳出循环if。如果找到这样的子字符串,则循环只会循环一次(如您所见)。如果没有这样的子字符串,它将无限循环,并且不打印任何内容。

相反,您应该将条件移动到循环本身,并继续更新index

while index != -1 and len(word) >= index + 3:
    print(word[index:index+3])
    index = word.find(character, index + 1)

推荐阅读