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

Question:

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
Asked By: Denis

||

Answers:

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)
Answered By: Harsh Kanjariya

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)
Answered By: Mureinik

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
Answered By: Maurice Meyer

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.

Answered By: Brakke Baviaan

The easiest way I think to simply printout all substrings within the string and apply the condition of len of strings as 3 and the starting character of the substring as 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)
Answered By: Nayan Shenoy
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.