在Python 3.5中,给出了这个字符串:
"rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
和索引17
- 所以,第二次出现F
时FooBar
- 我如何检查"FooBar"
是否存在?在这种情况下,它应该返回True,而如果我给它索引13
,它应该返回false。
答案 0 :(得分:5)
实际上有一种非常简单的方法可以在不使用任何额外内存的情况下执行此操作:
>>> s = "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
>>> s.startswith("FooBar", 17)
True
>>>
startswith
的可选第二个参数告诉它在偏移量17处开始检查(而不是默认值0)。在此示例中,值2也将返回True,所有其他值将返回False。
答案 1 :(得分:3)
您需要根据子字符串的长度对原始字符串进行切片并比较这两个值。例如:
>>> 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
答案 2 :(得分:2)
print("rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"[17:].startswith('Foo')) # True
或共同
my_string[start_index:].startswith(string_to_check)
答案 3 :(得分:0)
使用Tom Karzes方法,作为函数
def contains_at(in_str, idx, word):
return in_str[idx:idx+len(word)] == word
>>> contains_at(s, 17, "FooBar")
>>> True
答案 4 :(得分:0)
试试这个:
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)