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.)
回答 2
如果您要寻找的不是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())
string ="Samantha"
word ="man"def find_sub_string(word, string):
len_word = len(word)#returns 3for i in range(len(string)-1):if string[i: i + len_word]== word:returnTrueelse:returnFalse
Thought I would add this in case you are looking at how to do this for a technical interview where they don’t want you to use Python’s built-in function in or find, which is horrible, but does happen:
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
People mentioned string.find(), string.index(), and string.indexOf() in the comments, and I summarize them here (according to the Python Documentation):
First of all there is not a string.indexOf() method. The link posted by Deviljho shows this is a JavaScript function.
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.
回答 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")