我如何编写一个 python 程序,打印出所有至少三个字符长的子字符串?
How can I write a python program, which prints out all the substrings which are at least three characters long?
我需要编写程序,打印出所有长度至少为三个字符且以用户指定的字符开头的子字符串。
这是它应该如何工作的示例:
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
你刚刚开始了一个无限的 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)
你在进入if
后跳出循环。如果找到这样的子字符串,循环将只循环一次(如您所见)。如果没有这样的子字符串,它将无限循环,并且不打印任何内容。
相反,您应该将条件移动到循环本身,并继续更新index
:
while index != -1 and len(word) >= index + 3:
print(word[index:index+3])
index = word.find(character, index + 1)
find
returns 只是第一次出现,所以自己循环可能更容易:
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 中的可迭代对象,检查与提供的字符是否匹配,然后检查该字符是否具有至少 2 个前导字符,如果是,则打印结果并继续,直到字符串只剩下 2 个字符。
我需要编写程序,打印出所有长度至少为三个字符且以用户指定的字符开头的子字符串。 这是它应该如何工作的示例:
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
你刚刚开始了一个无限的 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)
你在进入if
后跳出循环。如果找到这样的子字符串,循环将只循环一次(如您所见)。如果没有这样的子字符串,它将无限循环,并且不打印任何内容。
相反,您应该将条件移动到循环本身,并继续更新index
:
while index != -1 and len(word) >= index + 3:
print(word[index:index+3])
index = word.find(character, index + 1)
find
returns 只是第一次出现,所以自己循环可能更容易:
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 中的可迭代对象,检查与提供的字符是否匹配,然后检查该字符是否具有至少 2 个前导字符,如果是,则打印结果并继续,直到字符串只剩下 2 个字符。