如何确定子string是否在不同的string中
我有一个子string:
substring = "please help me out" 我有另一个string:
 string = "please help me out so that I could solve this" 
 如何查找substring是否是使用Python的string的子集? 
 用in : substring in string : 
 >>> substring = "please help me out" >>> string = "please help me out so that I could solve this" >>> substring in string True 
 foo = "blahblahblah" bar = "somethingblahblahblahmeep" if foo in bar: # do something 
  (顺便说一下 – 不要试图命名variablesstring ,因为有一个Python标准库的名称相同,如果你在一个大型项目中这样做,你可能会混淆,所以避免这样的冲突是一个很好的习惯。 ) 
如果你正在寻找的不是真/假,你最好使用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()将返回string“请帮我”。 
 我想补充一点,如果你正在研究如何在技术面试中做到这一点,他们不希望你使用Python的内置函数或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 
 人们在注释中提到了string.find() , string.index()和string.indexOf() ,我在这里总结它们(根据Python文档 ): 
 首先没有一个string.indexOf()方法。  Deviljho发布的链接显示这是一个JavaScript函数。 
 其次, string.find()和string.index()实际上返回一个子串的索引。 唯一的区别是他们如何处理子string未find的情况: string.find()返回-1而string.index()引发一个ValueError 。 
你也可以尝试find()方法。 它确定stringstr是在string中还是在string的子string中出现。
 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 
 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() 
也可以使用这种方法
 if substring in string: print(string + '\n Yes located at:'.format(string.find(substring)))