简体   繁体   中英

Check if string contains substring at index

In Python 3.5, given this string:

"rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"

and the index 17 -- so, the F at the start of the second occurrence of FooBar -- how can I check that "FooBar" exists? In this case, it should return True, while if I gave it the index 13 it should return 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). In this example, a value of 2 will also return True, and all other values will return 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM