Slicing strings in Python to check if a string can become empty on recursive deletion


 Input: str = "GEEGEEKS", sub_str = "GEEKS" Output: Yes Explanation: In the string GEEGEEKSKS, we can first delete the substring GEEKS from position 4. The new string now becomes GEEKS. We can again delete sub-string GEEKS from position 1. Now the string becomes empty. Input: str = "GEEGEEKSSGEK", sub_str = "GEEKS" Output: No Explanation: In the string it is not possible to make the string empty in any possible manner. 

We have a solution to this problem, please refer to Check if a string can become empty by recursively deleting the given link to substring . We'll solve this problem in Python using isupper- lower-upper-swapcase-title /> find () search to search a substring for a given pattern.

  • If the substring is in the main string, find returns the index of its first occurrence.
  • Now split the string into two parts: (i) from the beginning of the string to index-1 of the found substring, (ii) (starting from the first index of the found substring + length of the substring) to the end of the string.
  • Combine these two sliced ​​pieces and repeat them from step 1 until the original string is empty or we find a substring.
  • # Function for checking, can whether the string becomes empty
    # recursively deleting the given substring


    def checkEmpty ( input , pattern):


      if len ( input ) = = 0 :

    return 'false'


      while ( len ( input )! = 0 ) :


    # find a substring in the main string

      index = input . find (pattern)


    # check if a substring was found or not

    if (index = = ( - 1 )):

    return 'false'


      # cut the input string in two and concatenate

      input = input [ 0 : index] + input [index + len (pattern):] 


      return 'true'

    # Driver program

    if __ name__ = = "__ main__" :

    input = 'GEEGEEKSKS'

      pattern = 'GEEKS'

      print checkEmpty ( input , pattern)



    Get Solution for free from DataCamp guru