How can I find the first occurrence of a sub-string in a python string?
Given the string "the dude is a cool dude",
I'd like to find the first index of 'dude':myst开发者_C百科ring.findfirstindex('dude') # should return 4
What is the python command for this?
find()
>>> s = "the dude is a cool dude"
>>> s.find('dude')
4
Quick Overview: index
and find
Next to the find
method there is as well index
. find
and index
both yield the same result: returning the position of the first occurrence, but if nothing is found index
will raise a ValueError
whereas find
returns -1
. Speedwise, both have the same benchmark results.
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
Additional knowledge: rfind
and rindex
:
In general, find and index return the smallest index where the passed-in string starts, and
rfind
andrindex
return the largest index where it starts Most of the string searching algorithms search from left to right, so functions starting withr
indicate that the search happens from right to left.
So in case that the likelihood of the element you are searching is close to the end than to the start of the list, rfind
or rindex
would be faster.
s.rfind(t) #returns: Same as find, but searched right to left
s.rindex(t) #returns: Same as index, but searches right to left
Source: Python: Visual QuickStart Guide, Toby Donaldson
to implement this in algorithmic way, by not using any python inbuilt function . This can be implemented as
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 = 'dude'
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 = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"
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))
精彩评论