Search code examples
pythonstringfindsubstring

How can I write a python program, which prints out all the substrings which are at least three characters long?


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

Solution

  • 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)