0

As you can see the program will ask the user for two string, it should ask for the longer string first then it needs to check the entire longer string for instances of the shorter string. If i find one, print out the index the match started at. and the program does this until it checked the entire longer string. I am new to python and I got stuck, if there are any suggestions please put it at a novice level so I understand without jumping into any advance techniques. This program should be cap sensitive as well. I am trying to find the shorter stringer and index it as many times as it appears (see projected output), by using slicing, indexing, and using a loop.

def main():
    longer = [input("First (longer) string: ")]
    shorter = input("Second (shorter) string: ")
    for shorter in longer:
        print("at index ","found a slice of ", shorter)

main

my projected output should be something like this:

longer: she sells seashells by the seashore.
shorter: sea

at index 10 found a slice of sea
at index 27 found a slice of sea
Alfred H.
  • 103
  • 1
  • 12

2 Answers2

0

Well, to get the first occurrence of the shorter string in the longer, you could use:

longer.find(shorter)

As requested in the comment below, you can write your own find method:

def find_str(s, char):
    index = 0

    if char in s:
        c = char[0]
        for ch in s:
            if ch == c:
                if s[index:index+len(char)] == char:
                    return index

            index += 1

    return -1

print(find_str("she sells seashells by the seashore", "sea"))
Karim Tabet
  • 1,789
  • 1
  • 14
  • 35
0

Please try this :

a = 'she sells seashells by the seashore'
b = 'sea'
for v in [ i.start() for i in re.finditer(r'' + b + '',a) ]:
    print "at index {0} found a slice {1}".format(v,b) 
Transhuman
  • 3,527
  • 1
  • 9
  • 15