Python : finding substring in a string

6 Oct

#!/usr/bin/python

import sys

def is_substring(actual_str, pattern_str):

    if actual_str is None or pattern_str is None:
        print "empty string .. quitting"
	return

    if len(pattern_str) > len(actual_str):
        print "substring pattern is longer than actual string"
	return

    indexes = []
    for i in range(len(actual_str) - len(pattern_str) + 1):
 	if pattern_str[0] == actual_str[i] and\
	    pattern_str[len(pattern_str)-1] == actual_str[i + len(pattern_str)-1]:
	    indexes.append(i)

    if len(indexes) == 0:
        print "Substring couldn't be found!"
	return

    mismatch = False
    for j in range(len(indexes)):
        index = indexes[j]
        for k in range(len(pattern_str)):
	    if(actual_str[index] != pattern_str[k]):
	        #print "Mismatch : %s - %s"%(actual_str[index], pattern_str[k])
		mismatch = True
		break
 	    index += 1

	if mismatch == True:
	    mismatch = False
	    continue
        print "substring found at indexes : ", indexes[j]

if __name__== "__main__":
    if len(sys.argv) != 3:
        is_substring('Hello world!', 'odl')
    else:
	is_substring(str(sys.argv[1]), str(sys.argv[2]))</div>

Output :

[harit@harit-laptop scripts]$ python substr.py ’123123113456456345123′ ’456′
substring found at indexes :  9
substring found at indexes :  12

[harit@harit-laptop scripts]$ python substr.py ‘Hello world!’ ‘orl’

substring found at indexes : 7

[harit@harit-laptop scripts]$ python substr.py 12 12

substring found at indexes : 0

[harit@harit-laptop scripts]$ python substr.py 12 123

substring pattern is longer than actual string

Advertisement

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.