Home > Back-end >  How can I write a python program, which prints out all the substrings which are at least three chara
How can I write a python program, which prints out all the substrings which are at least three chara

Time:10-27

I need to write program, which prints out all the substrings which are at least three characters long, and which begin with the character specified by the user. Here is an example how it should work:

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

My code looks like this and it doesn't properly work (it shows only 1 substring) :

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

CodePudding user response:

you just started an infinite while loop and stopped at first match

you can modify it to :

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)

CodePudding user response:

You break out of the loop after entering the if. If such a substring is found, the loop will only loop once (as you've seen). If there isn't such a substring, it will loop infinitely, and print nothing.

Instead, you should move the condition to the loop itself, and continue updating index as you go:

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

CodePudding user response:

find returns the first occurance only, so it might be easier to loop yourself:

word = 'mammoth'
character = 'm'

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

Out:

mam
mmo
mot

CodePudding user response:

Good day,

in order to achieve this, you'll have to build an algorithm. One way to build an algorithm that solves this problem, is to loop over all the characters in your string, and note that strings are iterable objects in python, check for matches with the supplied character, then check if that character has at least 2 leading characters, if so print the result and continue until the string has only 2 more characters left.

  • Related