[英]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 (ie) 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()
This will do it.这将做到。 Find the substring, and make sure it isn't at position 0 or at the end:
找到子字符串,并确保它不在位置 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 )
Followup跟进
I just realized this will fail if the string is found BOTH at the beginning and in the middle (as in "treesaregreentreesare").我刚刚意识到如果在开头和中间都找到字符串(如“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.
这将破坏和开始/结束比赛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.