Odpowiedzi:
z 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
, więcej tutaj
foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
# do something
(Przy okazji - staraj się nie nazywać zmiennej string
, ponieważ istnieje standardowa biblioteka Pythona o tej samej nazwie. Możesz zmylić ludzi, jeśli zrobisz to w dużym projekcie, więc unikanie takich kolizji jest dobrym nawykiem.)
Jeśli szukasz czegoś więcej niż prawda / fałsz, najlepiej będzie użyć modułu re, takiego jak:
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()
zwróci ciąg „proszę, pomóż mi”.
Pomyślałem, że dodam to na wypadek, gdybyś zastanawiał się, jak to zrobić na rozmowie technicznej, w której nie chcą, abyś używał wbudowanej funkcji Pythona in
lub find
, co jest okropne, ale się zdarza:
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
również, że zakres pętli powinien być lepszy, range(len(string)-len(substring))
ponieważ nie znajdziesz trzyliterowego słowa w dwóch ostatnich literach ciągu. (Zapisuje kilka iteracji).
Ludzie wspomnieli string.find()
, string.index()
iw string.indexOf()
komentarzach, a ja podsumowuję je tutaj (zgodnie z dokumentacją Pythona ):
Przede wszystkim nie ma string.indexOf()
metody. Link opublikowany przez Deviljho pokazuje, że jest to funkcja JavaScript.
Po drugie string.find()
i string.index()
faktycznie zwracają indeks podciągu. Jedyna różnica polega na tym, jak radzą sobie z sytuacją nie znalezionego podciągu: string.find()
zwraca, -1
gdy string.index()
podnosi ValueError
.
Możesz także wypróbować metodę find (). Określa, czy łańcuch str występuje w łańcuchu, czy w podłańcuchu łańcucha.
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")
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
Można również użyć tej metody
if substring in string:
print(string + '\n Yes located at:'.format(string.find(substring)))