1

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.

0

5 Answers 5

9

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2
print("rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"[17:].startswith('Foo')) # True

or in common

my_string[start_index:].startswith(string_to_check)

1 Comment

It’s correct but use more memory than the @Moinuddin Quadri’s answers, and a little slower ;-)
0

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

1 Comment

Thanks for the credit, but I realized there's a much better way to do this. See my answer :)
0

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)

2 Comments

Really not pythonic! Only useful to understand some basic concepts.
Indeed slicing maybe more useful (didn't think about it... This was the first thing that came to me) but this is still an answer to his question...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.