繁体   English   中英

我如何编写一个 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仅返回第一次出现,因此循环自己可能更容易:

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 个字符为止。

这就是我想出的:

str_input = str(input("Please type in a word:"))
count = len(str_input)
index = " "
while count > 0:
    char_input = str(input("Please type in a character:"))
    index = str_input.find(char_input)
    if (index + 3) < count:
         print(str_input[index:(index + 3)])
         break
    else:
         break

我认为最简单的方法是简单地打印出字符串中的所有子字符串,并将字符串的 len 条件应用为 3,并将 substring 的起始字符应用为 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM