查找子字符串是否包含在字符串中
Find if a substring is enclosed within a string
我想知道是否有一种直接的方法可以知道给定的子字符串是否存在于字符串中 strictly inbetween (即)不是 startswith 也不是 endswith 而是包含在字符串中的某个地方。
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 )
跟进
我刚刚意识到如果在开头和中间都找到字符串(如“treesaregreentreesare”),这将失败。这以不同的方式解决了这个问题:
for test in (input1,input2,input3,input4):
if substring in test[1:-1]:
print( True )
else:
print( False )
只需去掉第一个和最后一个字母。那会毁掉 start/end 比赛。
我想知道是否有一种直接的方法可以知道给定的子字符串是否存在于字符串中 strictly inbetween (即)不是 startswith 也不是 endswith 而是包含在字符串中的某个地方。
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 )
跟进
我刚刚意识到如果在开头和中间都找到字符串(如“treesaregreentreesare”),这将失败。这以不同的方式解决了这个问题:
for test in (input1,input2,input3,input4):
if substring in test[1:-1]:
print( True )
else:
print( False )
只需去掉第一个和最后一个字母。那会毁掉 start/end 比赛。