问题:如何确定子字符串是否在其他字符串中
我有一个子字符串:
substring = "please help me out"我还有另一个字符串:
string = "please help me out so that I could solve this"如何查找是否substring是string使用Python 的子集?
回答 0
用in:substring in string:
>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True回答 1
foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
    # do something(顺便说一句-尝试不命名变量string,因为存在一个具有相同名称的Python标准库。如果在大型项目中这样做,可能会使人们感到困惑,因此避免这种冲突是一种很好的习惯。)
回答 2
如果您要寻找的不是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() 将返回字符串“请帮助我”。
回答 3
我想我会在您不希望使用Python的内置函数inor的情况下进行技术面试时添加此内容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回答 4
人们提到了string.find()和string.index(),并string.indexOf()在评论中进行了总结(根据Python文档):
首先没有string.indexOf()方法。Deviljho发布的链接显示这是一个JavaScript函数。
其次,string.find()并string.index()实际上返回子字符串的索引。唯一的区别是它们如何处理子字符串没有发现的情况:string.find()回报-1而string.index()引发ValueError。
回答 5
您也可以尝试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")回答 6
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回答 7
def find_substring():
    s = 'bobobnnnnbobmmmbosssbob'
    cnt = 0
    for i in range(len(s)):
        if s[i:i+3] == 'bob':
            cnt += 1
    print 'bob found: ' + str(cnt)
    return cnt
def main():
    print(find_substring())
main()回答 8
也可以用这种方法
if substring in string:
    print(string + '\n Yes located at:'.format(string.find(substring)))回答 9
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。


