python - 如何编写一个 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
解决方案
进入后跳出循环if
。如果找到这样的子字符串,则循环只会循环一次(如您所见)。如果没有这样的子字符串,它将无限循环,并且不打印任何内容。
相反,您应该将条件移动到循环本身,并继续更新index
:
while index != -1 and len(word) >= index + 3:
print(word[index:index+3])
index = word.find(character, index + 1)
推荐阅读
- java - 无法配置 Spring Security
- python - 遍历具有范围的python列表中的项目列表
- c# - 获取 C# 中属性的值
- sorting - !在蛋糕php中以第一顺序显示空记录
- android - 我应该使用 RecyclerView.VERTICAL 而不是 LinearLayoutManager.VERTICAL?
- python - 将消息从容器发布到在容器外运行的 kafka
- javascript - Nodejs Http Server api 执行流程请解释一下?
- sql-server - SQL Server使用where子句获取下一个x行
- java - 为什么不会为实体自动生成数据库表
- asp.net-core-2.1 - 没有找到该网址的网页:http://localhost:64256/Registration.html