-1

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()
martineau
  • 119,623
  • 25
  • 170
  • 301
PIngu
  • 115
  • 1
  • 10
  • Are you looking for the `in` operator, perhaps? – Prune Jul 13 '21 at 21:56
  • 1
    `'substring' in 'string with substring'` → `True` – Klaus D. Jul 13 '21 at 21:57
  • no definitely not, as far as my understanding of python goes `in` operator just detects the presence of substring, not paying heed to whether it occurs at the beginning or end. What i want is in the middle, regardless of the occurrence at start and end. @Prune – PIngu Jul 13 '21 at 21:59
  • The combination of the three gives you the full logic, as does making the search on the string's middle. `if word in my_string[1:-1]` – Prune Jul 13 '21 at 23:17

1 Answers1

1

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.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30