How to determine whether a substring is in a different string
我有一个子串:
1 | substring ="please help me out" |
我还有一根绳子:
1 | string ="please help me out so that I could solve this" |
我如何确定
与
1 2 3 4 | >>> substring ="please help me out" >>> string ="please help me out so that I could solve this" >>> substring in string True |
1 2 3 4 | foo ="blahblahblah" bar ="somethingblahblahblahmeep" if foo in bar: # do something |
(顺便我尝试不到一
如果你想找一个以上的真/假,你会是最好的suited到使用re模块,如: </P >
1 2 3 4 5 | 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()) |
以为我会添加这个案例中你是在寻找如何做这个访谈的技术,他们不想让你打使用Python的内置函数或在
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |
这些人
第一部全有,是不是一个
第二次的
你也可以尝试的find()方法。它determines if occurs在字符串str字符串,或在一个字符串中的字符串。 </P >
1 2 3 4 5 6 7 | 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") |
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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() |
1 2 3 4 5 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 |
</P >
去大学的使用find(),一个简单的方式是使用""作为以上。 </P >
如果子串"是目前在战略中,然后将执行if部分另有其他部分会执行。 </P >
也可以使用这个方法。 </P >
1 2 3 | if substring in string: print(string + ' Yes located at:'.format(string.find(substring))) |