【发布时间】:2018-01-07 13:48:56
【问题描述】:
在 Python 3.5 中,给定这个字符串:
"rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
还有索引17——所以,F 在第二次出现FooBar 的开头——我如何检查"FooBar" 是否存在?在这种情况下,它应该返回 True,而如果我给它索引 13 它应该返回 false。
【问题讨论】:
在 Python 3.5 中,给定这个字符串:
"rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
还有索引17——所以,F 在第二次出现FooBar 的开头——我如何检查"FooBar" 是否存在?在这种情况下,它应该返回 True,而如果我给它索引 13 它应该返回 false。
【问题讨论】:
实际上有一种非常简单的方法可以做到这一点,而无需使用任何额外的内存:
>>> s = "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
>>> s.startswith("FooBar", 17)
True
>>>
startswith 的可选第二个参数告诉它在偏移量 17(而不是默认的 0)处开始检查。在此示例中,值 2 也将返回 True,所有其他值将返回 False。
【讨论】:
您需要根据子字符串的长度对原始字符串进行切片并比较两个值。例如:
>>> 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)
【讨论】:
使用 Tom Karzes 方法,作为函数
def contains_at(in_str, idx, word):
return in_str[idx:idx+len(word)] == word
>>> contains_at(s, 17, "FooBar")
>>> True
【讨论】:
试试这个:
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)
【讨论】: