[英]Check if string contains substring at index
在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.