How to determine whether a substring is in a different string

I have a sub-string:

substring = "please help me out"

I have another string:

string = "please help me out so that I could solve this"

How do I find if substring is a subset of string using Python?

214823 次浏览

with in: substring in string:

>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True
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
foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
# do something

(By the way - try to not name a variable string, since there's a Python standard library with the same name. You might confuse people if you do that in a large project, so avoiding collisions like that is a good habit to get into.)

如果你想要的不仅仅是真/假,那么你最好使用 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() will return the string "please help me out".

您也可以尝试 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")

人们在评论中提到了 string.find()string.index()string.indexOf(),我在这里总结一下(根据 Python 文档) :

首先没有 string.indexOf()方法,Deviljho 发布的链接显示这是一个 JavaScript 函数。

Second the string.find() and string.index() actually return the index of a substring. The only difference is how they handle the substring not found situation: string.find() returns -1 while string.index() raises an ValueError.

如果你正在研究如何在一个技术面试中做到这一点,他们不希望你使用 Python 的内置函数 infind,我想我应该加上这一点,这很糟糕,但确实发生了:

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
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()

Can also use this method

if substring in string:
print(string + '\n Yes located at:'.format(string.find(substring)))

enter image description here

不使用 find () ,一个简单的方法是使用上面的‘ in’。

如果‘ substring’出现在‘ str’中,那么 if part 将执行,否则 else part 将执行。