Search code examples
pythonstringsplitstartswithends-with

Find if a substring is enclosed within a string


I would like to know if there exists a direct way of knowing whether a substring given is present within a string strictly inbetween (i.e) not startswith and not endswith but somewhere contained within the string.

substring = "trees"

input1 = "sketchthetreesanddaffodils"
input2 = "treesaregreen"
input3 = "greentrees"
input4 = "greentreesareoftengreenertrees"

output1 = True 
output2 = False # 'trees' appearing at the beginning though
output3 = False # 'trees' appearing at the end though
output4 = True  # 'trees' appear in middle, regardless of the one in the end 

Expected operation

str.containsinmiddle()
#Something similar to str.startswith(), str.endswith()

Solution

  • This will do it. Find the substring, and make sure it isn't at position 0 or at the end:

    for test in (input1,input2,input3,input4):
        position = test.find(substring)
        if position >= 1 and position < len(test)-len(substring):
            print( True )
        else:
            print( False )
    

    Followup

    I just realized this will fail if the string is found BOTH at the beginning and in the middle (as in "treesaregreentreesare"). This solves the issue in a different way:

    for test in (input1,input2,input3,input4):
        if substring in test[1:-1]:
            print( True )
        else:
            print( False )
    

    Just strip off the first and last letters. That will ruin and start/end matches.