查找子字符串是否包含在字符串中



我想知道是否有一种直接的方法可以知道给定的子字符串是否存在于字符串中,严格地介于之间(即,不是startswitch和endswitch,而是包含在字符串中的某个位置(。

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 

预期操作

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

这样就可以了。找到子字符串,并确保它不在位置0或末尾:

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 )

后续

我刚刚意识到,如果字符串在开头和中间都找到(如"treesaregreteresare"(,这将失败。这以不同的方式解决了问题:

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

只需剥去第一个和最后一个字母。这会毁掉比赛并开始/结束比赛。

相关内容

最新更新