如何确定子字符串是否在不同的字符串中

sun*_*nny 105 python string

我有一个子字符串:

substring = "please help me out"
Run Code Online (Sandbox Code Playgroud)

我有另一个字符串:

string = "please help me out so that I could solve this"
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*coS 166

用in:substring in string:

>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True
Run Code Online (Sandbox Code Playgroud)

  • 天哪,python太强了,我觉得它需要一个函数来做它,但它是一个内置的一个Oo (10认同)

Amb*_*ber 20

foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
    # do something
Run Code Online (Sandbox Code Playgroud)

(顺便说一句 - 尝试不命名变量string,因为有一个同名的Python标准库.如果你在一个大型项目中这样做,你可能会混淆人们,因此避免这样的冲突是一个很好的习惯.)


小智 13

如果您要寻找的不仅仅是真/假,那么您最适合使用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())
Run Code Online (Sandbox Code Playgroud)

s.group() 将返回字符串"请帮助我".


Sam*_* Li 9

人们提到的string.find(),string.index()以及string.indexOf()在评论中,我(根据此总结他们的Python文档):

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

其次的string.find()和string.index()实际上返回一个字符串的索引.唯一的区别是他们如何处理子字符串未找到的情况:string.find()返回-1时string.index()引发一个ValueError.


小智 9

我想如果你正在考虑如何在技术面试中做这个,他们不希望你使用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
Run Code Online (Sandbox Code Playgroud)

  • 很好的例子,但你的身份是不正确的.为了加快速度,我会检查`如果len(substring)> len(string)返回False,那么循环范围最好是`range(len(string)-len(substring))`因为你找不到字符串的最后两个字母中的三个字母的单词.(保存几次迭代). (2认同)

Abh*_*pta 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")
Run Code Online (Sandbox Code Playgroud)