Answers:
用in
:substring in string
:
>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True
string.indexOf(substring) != -1
,更多的在这里
foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
# do something
(顺便说一句-尝试不命名变量string
,因为存在一个具有相同名称的Python标准库。如果在大型项目中这样做,可能会使人们感到困惑,因此避免这种冲突是一种很好的习惯。)
如果您要寻找的不是True / False,那么最适合使用re模块,例如:
import re
search="please help me out"
fullstring="please help me out so that I could solve this"
s = re.search(search,fullstring)
print(s.group())
s.group()
将返回字符串“请帮助我”。
我想我会在您不希望使用Python的内置函数in
or的情况下进行技术面试时添加此内容find
,这很可怕,但是确实发生了:
string = "Samantha"
word = "man"
def find_sub_string(word, string):
len_word = len(word) #returns 3
for i in range(len(string)-1):
if string[i: i + len_word] == word:
return True
else:
return False
if len(substring) > len(string) return False
循环范围,range(len(string)-len(substring))
因为在字符串的后两个字母中找不到三个字母。(节省一些迭代)。
您也可以尝试find()方法。它确定字符串str是出现在字符串中还是出现在字符串的子字符串中。
str1 = "please help me out so that I could solve this"
str2 = "please help me out"
if (str1.find(str2)>=0):
print("True")
else:
print ("False")
In [7]: substring = "please help me out"
In [8]: string = "please help me out so that I could solve this"
In [9]: substring in string
Out[9]: True
也可以用这种方法
if substring in string:
print(string + '\n Yes located at:'.format(string.find(substring)))