/  Technology   /  Python string is a substring of another one means? 

Python string is a substring of another one means? 

How to check if a given Python string is a substring of another one? 

Let’s understand this scenario with an example. We have been given two strings x and y. Now we have to check whether the given string y is a sub-string of the other string x

If y is a substring of x, then we return the index of its first occurrence and if not, then it will return -1.

 

Example:

x="Python with i2tutorials"
y="with"

x="Python with i2tutorials"
y="with"

 

Output:

             

 

We start traversing the string x and maintain an iterator(pointer), k for string y, from the 0th index.

We compare the current character in x for every iteration and check it with the index element where the iterator is currently present in y.

 

Example:

str[i] == key[k]

 

Output:

If matched, we increment the iterator k on y by 1. And if there’s a mismatch we re-initialise the iterator back to 0.

 

Example:

if (str[i] == key[k]):
          k +-1
      else:
          k = 0

 

Output;

We’ll have to keep an eye on the iterator position as when its value is equal to the length of string y, we break the execution there and return the value 

 

(iterator pointing index of string a – iterator pointing index of string b)

 

Example:

if (k == len(key)):
         break
return (i-k)

 

Output:

Now we’ll combine all these steps and write a program.

 

Example:

def sub_str(str, key):

   k = 0
   str_length = len(str)

   for i in ramge(str_length):
      if (k == len(key)):
         break
      if (str[i] == key[k]):
         k += 1
      else:
         k = 0

   if (k < len(key)):
      return -1
   else:
      return (i-k)

 

Output:

The advantage of this method is that it works efficiently which involves strings with duplicate characters.

Leave a comment