1

As I am a newbie ... not understanding why it's not working properly ? expecting the cause and solution and also tips thanks

str = "gram chara oi ranga matir poth"
find ='p'
l = len(str)
for x in range(0,l):
    if str[x]==find:         
        flag = x
        #break
if flag == x:
    print "found in index no",flag
else:
    print "not found in there"
2
  • 3
    try: print str.index(find);except: print "Not Found"; Commented Sep 12, 2016 at 17:39
  • @JoranBeasley thanks..... its new (try:except:) for me Commented Sep 17, 2016 at 9:58

3 Answers 3

2

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

I'd 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 you'll 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"
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, my intention was that if str[x] == find then save the index in flag my mistake was ....... the value of x is changing..in for loop
1

You're 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 won't 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"

Comments

1

Your method of searching is valid (iterating through the characters in the string). However, your problem is at the end when you're evaluating whether or not you've found the character. You're comparing flag to x, but when you do the comparison, x is out of scope. Because x is declared in a for loop statement, it's 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 you'll find the FIRST occurrence of find 

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.