【发布时间】:2025-11-21 17:40:01
【问题描述】:
我有一个子字符串:
substring = "please help me out"
我还有一个字符串:
string = "please help me out so that I could solve this"
如何使用 Python 查找 substring 是否是 string 的子集?
【问题讨论】:
我有一个子字符串:
substring = "please help me out"
我还有一个字符串:
string = "please help me out so that I could solve this"
如何使用 Python 查找 substring 是否是 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
【讨论】:
string.indexOf(substring) != -1,更多 here
substring 在string 中的位置,那么你想使用string.index
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
(顺便说一句 - 尽量不要命名变量 string,因为有一个同名的 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() 将返回字符串“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")
【讨论】:
人们在cmets中提到了string.find()、string.index()和string.indexOf(),我在这里总结一下(根据Python Documentation):
首先没有string.indexOf() 方法。 Deviljho 发布的链接显示这是一个 JavaScript 函数。
第二个string.find() 和string.index() 实际上返回子字符串的索引。唯一的区别是他们如何处理未找到子字符串的情况:string.find() 返回-1 而string.index() 引发ValueError。
【讨论】:
我想我会添加这个,以防你正在研究如何在技术面试中这样做,他们不希望你使用 Python 的内置函数 in 或 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)),因为你不会在字符串的最后两个字母中找到三个字母的单词。 (节省一些迭代)。
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)))
【讨论】: