如何编写一个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)

你刚刚开始了一个无限while循环,并在第一个匹配

可以修改为:

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

find只返回第一次出现,所以可能更容易自己循环:

word = 'mammoth'
character = 'm'
for x in range(0, len(word) - 2):
substr = word[x:x + 3]
if substr.startswith(character):
print(substr)

:

mam
mmo
mot

你好,

为了实现这一点,您必须构建一个算法。构建解决此问题的算法的一种方法是循环遍历字符串中的所有字符,并注意字符串在python中是可迭代的对象,检查是否与提供的字符匹配,然后检查该字符是否至少有两个前导字符,如果是,打印结果并继续直到字符串只剩下两个字符。

我认为最简单的方法是简单地打印出字符串中的所有子字符串并应用条件len of strings为3子字符串的起始字符为c

a = input()
b = input()
for i in range(0,len(a)):
c = a[i:i+3]
if c[0]==b and len(c)==3:
print(c)

最新更新