[英]Check if string contains substring at index
In Python 3.5, given this string: 在Python 3.5中,给出以下字符串:
"rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
and the index 17
-- so, the F
at the start of the second occurrence of FooBar
-- how can I check that "FooBar"
exists? 而该指数17
-因此,在F
在第二次出现的开始FooBar
-我怎么能检查"FooBar"
存在? In this case, it should return True, while if I gave it the index 13
it should return false. 在这种情况下,它应该返回True,而如果我给它提供索引13
它应该返回false。
There's actually a very simple way to do this without using any additional memory: 实际上,有一种非常简单的方法可以在不使用任何额外内存的情况下执行此操作:
>>> s = "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
>>> s.startswith("FooBar", 17)
True
>>>
The optional second argument to startswith
tells it to start the check at offset 17 (rather than the default 0). startswith
的可选第二个参数告诉它在偏移量17(而不是默认值0)处开始检查。 In this example, a value of 2 will also return True, and all other values will return False. 在此示例中,值2也将返回True,而所有其他值将返回False。
You need to slice your original string based on your substring's length and compare both the values. 您需要根据子字符串的长度对原始字符串进行切片,然后将两个值进行比较。 For example: 例如:
>>> my_str = "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
>>> word_to_check, index_at = "FooBar", 17
>>> word_to_check == my_str[index_at:len(word_to_check)+index_at]
True
>>> word_to_check, index_at = "FooBar", 13
>>> word_to_check == my_str[index_at:len(word_to_check)+index_at]
False
print("rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"[17:].startswith('Foo')) # True
或共同点
my_string[start_index:].startswith(string_to_check)
Using Tom Karzes approach, as a function 使用Tom Karzes方法,作为一个函数
def contains_at(in_str, idx, word):
return in_str[idx:idx+len(word)] == word
>>> contains_at(s, 17, "FooBar")
>>> True
Try this: 尝试这个:
def checkIfPresent(strng1, strng2, index):
a = len(strng2)
a = a + index
b = 0
for i in range(index, a):
if strng2[b] != strng1[i]:
return false
b = b+1
return true
s = "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
check = checkIfPresent(s, Foobar, 17)
print(check)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.