python – Find a character from a string without using find method?

python – Find a character from a string without using find method?

if flag == x looks strange. What value of x are you expecting there?

Id suggest instead initializing flag to None and then checking for it not being None at the end of the loop.

flag = None # assign a sentinel value here
str = gram chara oi ranga matir poth
find = p
for x in range(len(str)):
    if str[x] == find:         
        flag = x
        # Leaving out the break is also fine. It means youll print the
        # index of the last occurrence of the character rather than the first.
        break
if flag is not None:
    print found in index no, flag
else:
    print not found in there

Youre trying to have flag be the location of the index of the (first) matching character. Good!

if str[x]==find:
  flag = x
  break

But how to tell if nothing was found? Testing against x wont help! Try initializing flag to a testable value:

flag = -1
for x in range(0,l):
    if str[x]==find:         
        flag = x
        break

Now everything is easy:

if flag != -1:
    print found in index no,flag
else:
    print not found in there

python – Find a character from a string without using find method?

Your method of searching is valid (iterating through the characters in the string). However, your problem is at the end when youre evaluating whether or not youve found the character. Youre comparing flag to x, but when you do the comparison, x is out of scope. Because x is declared in a for loop statement, its only defined inside that for loop. So, to fix your code set an initial value for flag that you can check against, then change the check at the end:

flag = None
for x in range(len(str)):
    if str[x] == find:         
        flag = x
        break  # Using break here means youll find the FIRST occurrence of find 

if flag:
    print found in index no,flag
else:
    print not found in there

Leave a Reply

Your email address will not be published. Required fields are marked *