The find() is not recognising 'Bl' at index 0 as a substring. Neither when the string is 'Bl' nor when it is 'BlUeBe1Bl*fjal9jkl'. What could be the possible error in my code?
string = 'Bl'
#string = 'BlUeBe1Bl*fjal9jkl'
sub_string='Bl'
length=len(sub_string)
count=0
for i in range(0,len(string)-length+1):
if string.find(sub_string,i,i+length)>0:
count+=1
print(f'Count of {sub_string} in {string} is {count}')
When string = 'Bl' , the output should be 1 and when string = 'BlUeBe1Bl*fjal9jkl' , the output should be 2 but I am getting 0 and 1 respectively.
find() returns the index of the found occurance. If the start of the string matches the sub_string that you search for the result will be 0. You must check for >= 0 the fix the problem. find returns -1 when the sub_string is not found.
for i in range(0,len(string)-length+1):
if string.find(sub_string,i,i+length)>=0:
count+=1
find() function will return -1 when it does not found any match and 0 when it found match and you can achieve you solution by replacing this
if string.find(sub_string,i,i+length)>=0:
inside for loop .
for better understanding, please following link.
https://docs.python.org/2/library/string.html
string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.