如何确定子字符串是否在其他字符串中


107

我有一个子字符串:

substring = "please help me out"

我还有另一个字符串:

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

如何查找是否substringstring使用Python 的子集?

Answers:


169

insubstring in string

>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True

10
天哪,python太强大了,我以为它需要一个函数来完成,但是它是内置的Oo
windsound 2012年

我实际上是在学习Python之后才开始学习JS,为此,您需要添加if else语句和其他内容的负载。所以,我只是想提醒自己在Python中是如何完成的,这个答案让我对自己说:“当然!”,我的意思是在Python中这样的事情是如此琐碎,以至于他们从未想过!:P
游戏Brainiac

@GamesBrainiac其实,做同样的JS它只是string.indexOf(substring) != -1,更多的在这里
LasagnaAndroid

找到后,在字符串中存在子字符串,如何找到字符串在什么位置,如果子字符串在字符串中多次出现,会发生什么?
yoshiserry 2014年

@yoshiserry,如果您想在substringin中定位string,那么您要使用string.index
MarcoS 2014年

21
foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
    # do something

(顺便说一句-尝试不命名变量string,因为存在一个具有相同名称的Python标准库。如果在大型项目中这样做,可能会使人们感到困惑,因此避免这种冲突是一种很好的习惯。)


在那之后,不仅混淆而且破坏了所有引用字符串。
rplnt 2011年

13

如果您要寻找的不是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() 将返回字符串“请帮助我”。


1
有关正则表达式搜索的好技巧。
兰德尔·库克

在较轻的音符上。如果您尝试使用正则表达式解决问题,则尝试解决两个问题。
Hasan Iqbal

10

我想我会在您不希望使用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

2
很好的例子,但是您的身份不正确。为了加快速度,我还要检查if len(substring) > len(string) return False循环范围,range(len(string)-len(substring))因为在字符串的后两个字母中找不到三个字母。(节省一些迭代)。
AnyOneElse 2015年

9

人们提到了string.find()string.index(),并string.indexOf()在评论中进行了总结(根据Python文档):

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

其次,string.find()string.index()实际上返回子字符串的索引。唯一的区别是它们如何处理子字符串没有发现的情况:string.find()回报-1string.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")


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

在给定的字符串中找到子字符串“ bob”。
avina k

0

也可以用这种方法

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

0

在此处输入图片说明

除了使用find()之外,一种简单的方法是如上所述使用'in'。

如果'str'中存在'substring',则将执行part,否则执行part。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.