Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查字符串是否在索引处包含子字符串_Python_String_Substring - Fatal编程技术网

Python 检查字符串是否在索引处包含子字符串

Python 检查字符串是否在索引处包含子字符串,python,string,substring,Python,String,Substring,在Python 3.5中,给定以下字符串: "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj" 索引17——那么,第二次出现FooBar时的F——我如何检查“FooBar”是否存在?在这种情况下,它应该返回True,而如果我给它索引13,它应该返回false。您需要根据子字符串的长度对原始字符串进行切片,并比较两个值。例如: >>> my_str = "rsFooBargrdshtrshFooBargreshyershytreB

在Python 3.5中,给定以下字符串:

"rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"

索引
17
——那么,第二次出现
FooBar
时的
F
——我如何检查
“FooBar”
是否存在?在这种情况下,它应该返回True,而如果我给它索引
13
,它应该返回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
或者共同点

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)

实际上,有一种非常简单的方法可以在不使用任何额外内存的情况下执行此操作:

>>> s = "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
>>> s.startswith("FooBar", 17)
True
>>> 

startswith
的可选第二个参数告诉它在偏移量17(而不是默认的0)处开始检查。在本例中,值2也将返回True,所有其他值将返回False。

这是正确的,但比@Moinuddin Quadri的答案使用更多内存,速度稍慢;-)真的不是蟒蛇!只对理解一些基本概念有用。事实上,切片可能更有用(我没有想到……这是我想到的第一件事),但这仍然是对他的问题的回答……谢谢你的赞扬,但我意识到有更好的方法来做这件事。见我的答案:)
>>> s = "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
>>> s.startswith("FooBar", 17)
True
>>>