Yanıtlar:
>>> s = "the dude is a cool dude"
>>> s.find('dude')
4
iscümledeki kelimeyi bulmak istersem ne olur this is a cool dude? Find yöntemini denedim ama 5 yerine dizin 2 döndürüyor. Bunu find () kullanarak nasıl başarabilirim?
indexvefindYanındaki findbir yöntem de yoktur index. findve indexher ikisi de aynı sonucu verir: ilk oluşumun konumunu döndürmek, ancak hiçbir şey bulunmazsa index, a ValueErrorwhile finddöndürür -1. Hız açısından her ikisi de aynı kıyaslama sonuçlarına sahiptir.
s.find(t) #returns: -1, or index where t starts in s
s.index(t) #returns: Same as find, but raises ValueError if t is not in s
rfindve rindex:Genel olarak, bulmak ve dizin geçti-string başlar en küçük indeksi dönün ve
rfindverindexbu arama algoritmaları gelen arama dize çoğu başlar büyük dizin dönmek soldan sağa başlayarak fonksiyonları böylece,rarama bulunsa belirtmek sağ sola .
Dolayısıyla, aradığınız öğenin olasılığının listenin başlangıcına göre sona yakın olması rfindveya rindexdaha hızlı olması durumunda.
s.rfind(t) #returns: Same as find, but searched right to left
s.rindex(t) #returns: Same as index, but searches right to left
Kaynak: Python: Visual QuickStart Guide, Toby Donaldson
input_string = "this is a sentence"ve sözcüğün ilk geçtiği yeri bulmak istiyorsak is, o zaman işe yarayacak mı? # first occurence of word in a sentence input_string = "this is a sentence" # return the index of the word matching_word = "is" input_string.find("is")
herhangi bir python dahili işlevi kullanmayarak bunu algoritmik bir şekilde uygulamak için. Bu şu şekilde uygulanabilir:
def find_pos(string,word):
for i in range(len(string) - len(word)+1):
if string[i:i+len(word)] == word:
return i
return 'Not Found'
string = "the dude is a cool dude"
word = 'dude1'
print(find_pos(string,word))
# output 4
def find_pos(chaine,x):
for i in range(len(chaine)):
if chaine[i] ==x :
return 'yes',i
return 'no'
verse = "Her şey seninle ilgiliyken kafanı tutabiliyorsan \ n Onları kaybediyor ve seni suçluyorsan, \ nEğer herkes senden şüphe ettiğinde kendine güvenebilirsen, \ n Ama onların şüphelerini de hesaba kat; \ nEğer yapabilirsen bekle ve bekleyerek yorulma, \ n Veya yalan söylenerek, yalanlarla uğraşma, \ nYa da nefret edilme, nefrete yer verme \ n Yine de çok iyi görünme ve çok akıllıca konuşma :"
enter code here
print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))
-1bulunmazsa eğer